How does Thread.__init__(self) in a class work?

前端 未结 2 1282
别那么骄傲
别那么骄傲 2021-01-03 14:49

So I found this code:

from threading import Thread
class Example(Thread):
    def __init__(self):
        Thread.__init__(self)

    def run (self):
                 


        
2条回答
  •  有刺的猬
    2021-01-03 15:07

    Your __init__ method is entirely redundant. You are in effect replacing Thread.__init__() with your own implementation, where your own implementation simply calls Thread.__init__(). If you removed it, nothing would change:

    class Example(Thread):
        def run (self):
            print("It works!")
    

    Your Example.run() method is simply called because you started the thread using the Thread.start() method:

    start()
    Start the thread’s activity.

    It must be called at most once per thread object. It arranges for the object’s run() method to be invoked in a separate thread of control.

    Also see the Thread.run() documentation:

    run()
    Method representing the thread’s activity.

    You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with sequential and keyword arguments taken from the args and kwargs arguments, respectively.

    Your __init__ method had nothing to do with that.

    Now, if you created a __init__ method in a Thread subclass and then did not make sure Thread.__init__ was called, then you prevented the class from setting important instance information, breaking instances:

    >>> from threading import Thread
    >>> class Example(Thread):
    ...     def run (self):
    ...         print("It works!")
    ... 
    >>> Example().start()
    It works!
    
    >>> class BrokenExample(Thread):
    ...     def __init__(self):
    ...         # not doing anything
    ...         pass
    ...     def run (self):
    ...         print("It works!")
    ... 
    >>> BrokenExample().start()
    Traceback (most recent call last):
      File "", line 1, in 
      File "/.../lib/python2.7/threading.py", line 737, in start
        raise RuntimeError("thread.__init__() not called")
    RuntimeError: thread.__init__() not called
    

    Because this is a common error to make, the Thread.start method throws a custom exception to tell you explicitly that Thread.__init__ was not executed.

提交回复
热议问题