【发布时间】:2020-10-27 13:27:36
【问题描述】:
我正在尝试使用 python 套接字和线程库创建一个简单的程序。我想使用装饰器自动化以下过程:
t = threading.Thread(target=function, args=(arg1, arg2))
t.start()
程序是使用 OOP 构造的,所以我在主类中定义了一个子类来包含所有装饰器(我在本文中读到了这个方法:https://medium.com/@vadimpushtaev/decorator-inside-python-class-1e74d23107f6)。所以我有这样的情况:
class Server(object):
class Decorators(object):
@classmethod
def threaded_decorator(cls, function):
def inner_function():
function_thread = threading.Thread(target=function)
function_thread.start()
return inner_function
def __init__(self, other_arguments):
# other code
pass
@Decorators.threaded_decorator
def function_to_be_threaded(self):
# other code
pass
但是当我尝试运行时,我收到以下错误:TypeError: function_to_be_threaded() missing one required argument: 'self'。我怀疑问题出在我调用 threading.Thread(target=function) 时的部分,它以某种方式没有传递整个函数 self.function_to_be_thread。因此,如果您知道如何解决此问题,请告诉我吗?另外,你能告诉我是否有办法实现一个接受参数的装饰器,该参数将作为args=(arguments_of_the_decorator)传递给 Thread 类?
非常感谢您的时间,原谅我的英语,我还在练习它
【问题讨论】:
标签: python multithreading python-multithreading python-decorators