[Python] Using python decorators associated with an instance level object

Discussão em 'Python' iniciado por Stack, Julho 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create a decorator which enables me to register callback functions to an instance of ClassB. I would like to use this decorator in other classes within my program (eg. ClassA) but want to instantiate ClassB as an instance variable of ClassA instead of instantiating it as a module level variable. When instantiating at module level everything works fine, however when instantiating as an instance variable of ClassA it fails.

    class ClassB():

    def __init__(self):
    self.callbacks = []

    def register_callback(self):
    def wrapper(fn):
    self.callbacks.append(fn)
    return fn
    return wrapper


    Instantiating at module level works well:

    import ClassB

    class_b = ClassB()

    class ClassA():

    def __init__(self):
    pass

    @class_b.register_callback()
    def do_something(self):
    # do stuff



    Instantiating as an instance variable does not work:

    import ClassB

    class ClassA():

    def __init__(self):
    self.class_b = SomeClassB()

    @self.class_b.register_callback()
    def do_something(self):
    # do stuff



    What is the correct syntax/ way to achieve what I am trying to do?

    Continue reading...

Compartilhe esta Página