Python构造函数的子类化过程

Rat*_*Don 7 python initialization class

我正在尝试创建一个对象作为一个新进程.如果我给类的构造函数,程序显示错误.

import multiprocessing as mp 
import time

class My_class(mp.Process):
    def __init__(self):
            self.name = "Hello "+self.name
            self.num = 20

    def run(self):
        print self.name, "created and waiting for", str(self.num), "seconds"
        time.sleep(self.num)
        print self.name, "exiting"

if __name__ == '__main__':
    print 'main started'
    p1=My_class()
    p2=My_class()
    p1.start()
    p2.start()  
    print 'main exited'
Run Code Online (Sandbox Code Playgroud)

错误

File "/usr/lib64/python2.7/multiprocessing/process.py", line 120, in start
    assert self._popen is None, 'cannot start a process twice'
AttributeError: 'My_class' object has no attribute '_popen'
Run Code Online (Sandbox Code Playgroud)

但是,当插入行super(My_class, self).__init__()super(My_class, self).__init__(),在程序运行的罚款.

最终构造函数:

def __init__(self):
    super(My_class, self).__init__()
    self.name = "Hello "+self.name
    self.num = 20
Run Code Online (Sandbox Code Playgroud)

我在不同的上下文中找到了这一行,并在这里尝试并且代码工作正常.

任何人都可以解释super(My_class, self).__init__()上面构造函数中该行的工作是什么?

aga*_*rs3 11

当您添加自己的__init__()位置,你是压倒一切__init__()超类.但是,超类经常(在这种情况下)有一些它需要的东西__init__().因此,你要么必须重新创建功能(例如初始化_popen为你的错误描述,除其他事项外),或调用父类的构造函数使用新的构造super(My_class, self).__init__()(或super().__init__()在Python 3).