Search code examples
pythonclassinitialization

Python subclassing process with initialiser


I'm trying to create a object as a new process. If I give an initialiser to the class, program is showing an error.

Code

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'

Error

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'

But when a insert the line super(My_class, self).__init__() to the initialiser, the program is running fine.

Final constructor:

def __init__(self):
    super(My_class, self).__init__()
    self.name = "Hello "+self.name
    self.num = 20

I found that line in a different context and tried here and the code is working fine.

Can anybody please explain what is the work of the line super(My_class, self).__init__() in the above initialiser?


Solution

  • When you add your own __init__() here, you are overriding the __init__() in the superclass. However, the superclass often (as in this case) has some stuff it needs in its __init__(). Therefore, you either have to re-create that functionality (e.g. initializing _popen as described in your error, among other things), or call the superclass constructor within your new constructor using super(My_class, self).__init__() (or super().__init__() in Python 3).