Reputation: 309
I'm curious why I can't call super(Thread, self).__init__()
instead of Thread.__init__(self)
when my class inherits from Thread. Can you help me to understand the problem?
#!/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()
Upvotes: 0
Views: 4027
Reputation: 365965
I'm curious why I can't call
super(Thread, self).__init__()
instead ofThread.__init__(self)
when my class inherits fromThread
.
Because that's not how super
works. You have to pass your own type as the first parameter, so it can search for the next ancestor of that type. If you pass it Thread
, you're asking for an ancestor of Thread
.
If your parent class is a regular new-style Python class, doing this wrong usually means you skip over one ancestor class, which may be harmless, or may seem to work but not actually do the right thing. But threading.Thread
has specific checks to make sure it gets initialized properly, so you're probably getting something like this:
AssertionError: Thread.__init__() was not called
If your parent class is a C extension class, it probably doesn't have any ancestors, and it probably doesn't implement super
even if it does, so you'll usually get an error that way too.
You may want to read Python's super() considered super if you want to understand how all of this works (because the docs linked above aren't necessarily the best introductory discussion).
So, in summary:
super(Worker, self).__init__()
Upvotes: 3