Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple inheritance along with threading in python

I have a code sample which is very similar to following

import threading
import datetime
import time
import sys

class FirstClass(object):
    def __init__(self):
        print 'initialized'

class ThreadClass(FirstClass, threading.Thread):
    def __init__(self):
        super(ThreadClass, self).__init__()
        print 'initialized2'

    def run(self):
        time.sleep(1)
        now = datetime.datetime.now()
        sys.stdout.write("%s says Hello World at time: %s \n" % (self.getName(), now))

for i in range(20):
    t = ThreadClass()
    t.start()

Due to call-next-method of python I am not able to run init method of both FirstClass and thread. Is there any alternate way through which I can solve this issue.

like image 397
raju Avatar asked Nov 14 '12 14:11

raju


1 Answers

You'll need to call super(FirstClass, self).__init__() in the FirstClass.__init__() initializer too.

The whole point of using super() is to make passing on the call to a parent cooperative. In your specific MRO FirstClass is listed before threading.Thread, so without explicitly calling the next __init__ in MRO order threading.Thread.__init__() never gets invoked.

You may want to look at the excellent PyCon 2015 presentation by Raymond Hettinger on how super() works in this context.

like image 118
Martijn Pieters Avatar answered Oct 07 '22 08:10

Martijn Pieters