[Python] How to access constructor variables in python decorator?

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    I have created a class and declared some variables inside it's constructor.

    This class also has some methods.

    I have also created a decorator which takes a parameter.

    What I want is to use that decorator before those methods and pass one of the variable from the class constructor.

    Below is my code:

    Decorator:

    def thread_switch_decorator(argument):
    def decorator(function):
    def wrapper(*args, **kwargs):
    argument.stop()
    result = function(*args, **kwargs)
    argument.start()
    return result

    return wrapper

    return decorator


    Class and Methods:

    class MainWindow(QMainWindow):
    def __init__(self):
    self.my_thread = initiate_connect()

    @thread_switch_decorator(argument=self.my_thread) # <--- Here is the problem
    def home_page(self):
    pass


    Error:

    @thread_switch_decorator(argument=self.my_thread)
    NameError: name 'self' is not defined


    On the code above where I am using the decorator I can not pass the parameter from the constructor. Which is logical.

    My question is, how can I do this?

    Continue reading...

Compartilhe esta Página