[Python] Overriding __setattr__ at runtime

Discussão em 'Python' iniciado por Stack, Abril 24, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to override the __setattr__ method of a Python class, since I want to call another function each time an instance attribute changes its value. However, I don't want this behaviour in the __init__ method, because during this initialization I set some attributes which are going to be used later:

    So far I have this solution, without overriding __setattr__ at runtime:

    class Foo(object):
    def __init__(self, a, host):
    object.__setattr__(self, 'a', a)
    object.__setattr__(self, 'b', b)
    result = self.process(a)
    for key, value in result.items():
    object.__setattr__(self, key, value)

    def __setattr__(self, name, value):
    print(self.b) # Call to a function using self.b
    object.__setattr__(self, name, value)


    However, I would like to avoid these object.__setattr__(...) and override __setattr__ at the end of the __init__ method:

    class Foo(object):
    def __init__(self, a, b):
    self.a = a
    self.b = b
    result = self.process(a)
    for key, value in result.items():
    setattr(self, key, value)
    # override self.__setattr__ here

    def aux(self, name, value):
    print(self.b)
    object.__setattr__(self, name, value)


    I have tried with self.__dict__['__setitem__'] = self.aux and object.__setitem__['__setitem__'] = self.aux, but none of these attemps has effect. I have read this section of the data model reference, but it looks like the assignment of the own __setattr__ is a bit tricky.

    How could be possible to override __setattr__ at the end of __init__, or at least have a pythonic solution where __setattr__ is called in the normal way only in the constructor?

    Continue reading...

Compartilhe esta Página