【问题标题】:Threading Decorator [Python]线程装饰器 [Python]
【发布时间】: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


    【解决方案1】:

    使用*args 语法移动参数。换句话说,使用*args 将所有位置参数收集为一个元组并将threading.Thread 移动为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?

    【讨论】:

    • 非常感谢 napuzba 抽出宝贵时间,非常感谢:我试过了,效果很好!
    猜你喜欢
    • 1970-01-01
    • 2017-01-11
    • 2012-12-23
    • 2016-09-09
    • 1970-01-01
    • 2013-08-07
    • 2014-01-23
    • 1970-01-01
    相关资源
    最近更新 更多