스레딩 데코레이터 [Python]

Oct 27 2020

파이썬 소켓과 스레딩 라이브러리를 사용하여 간단한 프로그램을 만들려고합니다. 데코레이터를 사용하여 다음 절차를 자동화하고 싶습니다.

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'합니다.. 어떻게 든 전체 함수 self.function_to_be_threaded를 전달하지 않는 threading.Thread (target = function)을 호출 할 때 문제가 부분에 있다고 생각합니다. 따라서이 문제를 해결하는 방법을 안다면 알려주세요. 또한 Thread 클래스에 전달할 인수를 허용하는 데코레이터를 구현하는 방법이 있는지 알려 주실 수 args=(arguments_of_the_decorator)있습니까?

시간 내 주셔서 감사합니다. 실례합니다. 아직 연습 중입니다.

답변

1 napuzba Oct 27 2020 at 15:15

*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

한 함수에서 다른 함수로 인수를 어떻게 전달할 수 있습니까?를 참조하십시오 .