线程装饰器[Python] [英] Threading Decorator [Python]

查看:12
本文介绍了线程装饰器[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]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆