简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM