Threading Decorator [Python](线程装饰器[Python])
本文介绍了线程装饰器[Python]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试使用python套接字和线程库创建一个简单的程序。我想使用一个装饰器自动执行以下步骤:
t = threading.Thread(target=function, args=(arg1, arg2))
t.start()
程序是使用OOP构建的,所以我在Main中定义了一个子类来包含所有的修饰符(我在本文中读到了这个方法: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(目标=函数)时,问题出在没有传递整个函数self.unction_to_be_threaded的部分中。因此,如果你知道如何解决这个问题,你能告诉我吗?另外,您能告诉我是否有一种方法可以实现一个接受参数的修饰符,该参数将作为args=(arguments_of_the_decorator)传递给Thread类?
非常感谢您抽出时间并原谅我的英语,我还在练习
推荐答案
使用*args语法移动参数。换言之,使用*args将所有位置参数收集为一个元组,并将其作为args移动。
import threading
import time
class Server(object):
class Decorators(object):
@classmethod
def threaded_decorator(cls, function):
def inner_function(*args):
function_thread = threading.Thread(target=function,args=args)
function_thread.start()
return inner_function
def __init__(self, count,sleep):
self.count = count
self.sleep = sleep
@Decorators.threaded_decorator
def function_to_be_threaded(self,id):
for xx in range(self.count):
time.sleep(self.sleep)
print("{} ==> {}".format(id,xx))
>>> Server(6,1).function_to_be_threaded('a')
>>> Server(2,3).function_to_be_threaded('b')
a ==> 0
a ==> 1
a ==> 2
b ==> 0
a ==> 3
a ==> 4
a ==> 5
b ==> 1
另见How can I pass arguments from one function to another?
这篇关于线程装饰器[Python]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:线程装饰器[Python]
基础教程推荐
猜你喜欢
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
