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

前端 未结 2 1295
别那么骄傲
别那么骄傲 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:25

    __init__() method is called when an object is initialized. And when you do - Thread.__init__(self) , it just just calling the parent class' __init__() method .

    Like said in comment you can remove it and the functionality should remain same. In your class the __init__() is completely redundant.

    This method is called when you do -

    Example()
    

    When you create the new object for Example() .

    The run() method is called, when you do - .start() on the Example() object. This is done by the Thread.start() method, from documentation -

    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.


    Adding one more print statement and dividing Example().start() into two lines so you can understand this clearly -

    >>> from threading import Thread
    >>> class Example(Thread):
    ...     def __init__(self):
    ...         Thread.__init__(self)
    ...         print("In __init__")
    ...     def run (self):
    ...         print("It's working!")
    ...
    >>> e = Example()
    In __init__
    >>> e.start()
    It's working!
    

提交回复
热议问题