[英]Calling a super class constructor when inheriting from Thread
我很好奇為什么我的類從線程繼承時不能調用super(Thread, self).__init__()
而不是Thread.__init__(self)
。 您能幫我理解問題嗎?
#!/usr/bin/python
from threading import Thread
from Queue import Queue
class ThreadManager(object):
def work(self, items):
q = Queue()
for item in items:
q.put(item)
print q.qsize()
p = Worker()
p.start()
p.join()
class Worker(Thread):
def __init__(self):
# Why doesn't this work?
#super(Thread, self).__init__()
Thread.__init__(self)
def run(self):
print 'thread running'
def main():
items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']
tm = ThreadManager()
tm.work(items)
if __name__ == "__main__":
main()
我很好奇為什么我的類從
Thread
繼承時不能調用super(Thread, self).__init__()
而不是Thread.__init__(self)
。
因為那不是super
工作原理。 您必須傳遞自己的類型作為第一個參數,以便它可以搜索該類型的下一個祖先。 如果您將其傳遞給Thread
,則您需要Thread
的祖先。
如果您的父類是常規的新式Python類,則執行此錯誤通常意味着您跳過了一個祖先類,這可能是無害的,或者似乎可以工作,但實際上並沒有做正確的事情。 但是threading.Thread
具有特定的檢查以確保正確初始化,因此您可能會得到如下所示的信息:
AssertionError: Thread.__init__() was not called
如果您的父類是C擴展類,則它可能沒有任何祖先,並且即使實現了它也可能不會實現super
,因此您通常也會以這種方式得到錯誤。
如果您想了解所有方法的工作原理,則可能需要閱讀被認為是super的Python的super() (因為上面鏈接的文檔不一定是最佳的入門討論)。
因此,總而言之:
super(Worker, self).__init__()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.