[英]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. 由于python的call-next-method,我无法运行FirstClass和thread的init方法。 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. 你需要在FirstClass.__init__()
初始化程序中调用super(FirstClass, self).__init__()
。
The whole point of using super()
is to make passing on the call to a parent cooperative. 使用super()
是将调用传递给父协作。 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. 在你的特定MRO中,在threading.Thread
之前列出了FirstClass
,所以没有在MRO命令中明确调用下一个__init__
。 threading.Thread.__init__()
永远不会被调用。
You may want to look at the excellent PyCon 2015 presentation by Raymond Hettinger on how super()
works in this context. 您可能想看一下Raymond Hettinger关于super()
在这种情况下如何工作的优秀PyCon 2015演示文稿 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.