开发者

Is there a problem with inheriting from threading.Thread without actually starting the thread?

开发者 https://www.devze.com 2023-02-27 11:02 出处:网络
I\'ve created a Python class which inherits from threading.Thread, instances of which may not actually be run as a new thread (because the start() method is never invoked). The code has been written s

I've created a Python class which inherits from threading.Thread, instances of which may not actually be run as a new thread (because the start() method is never invoked). The code has been written such that it works whether start() has been invoked or not (just in a slightly different way). This is entirely intentional.

Is there a problem or over开发者_Python百科head with not ever invoking the start() method on an instance of the class? Is there a better way to write a class that is sometimes run in a new thread and sometimes not?

Inheriting from Thread insists on appending a Thread-n to the repr() string on the class instance, even if it isn't running.


In my view a slightly cleaner design would be to not inherit your class from threading.Thread, but keep its run method as-is.

Now:

  • if you don't need threading, you can continue to use your class as you do currently;
  • if you do need threading, create a new Thread object, setting the target= constructor argument to your object's run method.
0

精彩评论

暂无评论...
验证码 换一张
取 消