简体   繁体   中英

method vs __init__ in a python class

My understanding of these methods are:

  • __init__() is like constructor.
  • run() is called when a thread for this class starts.

But why do we need a run method? Could we have instantiated an object of the class and all initializations stay in __init__() ?

I have gone through this article , could not make much out of it Can you please share some insights on this ?

I think the Python threading module provides a good example. What if you had a derived thread class that always ran the same function, but perhaps you want to give it different inputs. You might want to instantiate a lot of objects of the class but with differing inputs -- and you don't want it to start running yet.

Maybe you want to pass this list of instantiated (but not started) threads to some kind of manager that starts and monitors them regardless of what kind of thread they are.

In that case it is good to separate the creation from the run.

__init__ runs once (when the object is constructed), while run (in the example you gave) runs in the background (another process) as long as the object exists.

The only difference between __init__ and run are that the first runs in the main thread, while the second runs in another thread.

But why do we need a run method ? we may have instansiated an object of class and all initializations stay in__init__ ?

In fact, all inializations are already in __init__. the run method in that example just demonstrates a background thread, and is not necessary.

You are correct about __init__() being a constructor. In this example, the goal is to run a function, the run() function, in a thread. The example provides a clean way of doing this. You cannot run the code inside the run() function inside the __init__() , as this would not spawn a new thread.

Consider the case:

example = ThreadingExample()
do_something_important_that_doesnt_want_to_wait()

This works with the example code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM