[Python] Decorate setter property of a class

Discussão em 'Python' iniciado por Stack, Maio 29, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class Tracker defined as below:

    class Tracker():
    def __init__(self):
    self._value = None

    @property
    def value(self):
    return self._value

    @value.setter
    def value(self, value):
    self._value = value


    Then I have another class Aggregator, defined as below. This class takes instances of Tracker defined above.

    class Aggregator():
    def __init__(self,trackers):
    self.trackers = trackers

    def updator(func):
    def wrapper(*args): # this function will be used to wrap the Tracker.value property/descriptor
    return_value = func(*args)
    self.update() # Call Aggregator.update() method
    return return_value
    return wrapper

    for t in trackers: # list of tracker objects
    t.value = updator(t.value) # Causes errors since the t.value no longer references the method but is used to get/set the value
    t.__class__.__dict__['value'].fset = updator(t.__class__.__dict__['value'].fset) # Causes AttributeError: readonly attribute


    def update(self):
    self.value = sum([t.value for t in self.trackers])


    I understand why this is happening. My problem is this: how do I decorate the Tracker.value (property/descriptor) so updating a value in any tracker will trigger the Aggregator.update method of the object that includes that tracker?

    Continue reading...

Compartilhe esta Página