थ्रेडिंग डेकोरेटर [पायथन]

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':। मुझे संदेह है कि जब मैं थ्रेडिंग कहता हूं तो यह समस्या उस भाग में स्थित है। थ्रेड (लक्ष्य = फ़ंक्शन) जो किसी भी तरह से पूरे फ़ंक्शन को स्वयं नहीं करता है। function_to_be_threaded। इसलिए, यदि आप इसे ठीक करना जानते हैं, तो कृपया मुझे बता सकते हैं? इसके अलावा, क्या आप मुझे बता सकते हैं कि क्या एक डेकोरेटर को लागू करने का एक तरीका है जो तर्क को स्वीकार करता है जो थ्रेड क्लास को पास करेगा args=(arguments_of_the_decorator)?

आपके समय के लिए बहुत बहुत धन्यवाद और मेरी अंग्रेजी को बहाना, मैं अभी भी इसका अभ्यास कर रहा हूं

जवाब

1 napuzba Oct 27 2020 at 15:15

उपयोग *argsवाक्य रचना arguments.In दूसरे शब्दों में, उपयोग स्थानांतरित करने के लिए *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

यह भी देखें कि मैं एक फ़ंक्शन से दूसरे फ़ंक्शन में तर्क कैसे पारित कर सकता हूं?