title: Overriding __setattr__ at runtime
body: <p>I am trying to override the <code>__setattr__</code> 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 <code>__init__</code> method, because during this initialization I set some attributes which are going to be used later:</p>
  
  <p>So far I have this solution, without overriding <code>__setattr__</code> at runtime:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>However, I would like to avoid these <code>object.__setattr__(...)</code> and override <code>__setattr__</code> at the end of the <code>__init__</code> method:</p>
  
  <pre><code>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)
  </code></pre>
  
  <p>I have tried with <code>self.__dict__['__setitem__'] = self.aux</code> and <code>object.__setitem__['__setitem__'] = self.aux</code>, but none of these attemps has effect. I have read <a href="http://docs.python.org/2/reference/datamodel.html#object.__setattr__" rel="noreferrer">this section of the data model reference</a>, but it looks like the assignment of the own <code>__setattr__</code> is a bit tricky.</p>
  
  <p>How could be possible to override <code>__setattr__</code> at the end of <code>__init__</code>, or at least have a pythonic solution where <code>__setattr__</code> is called in the normal way only in the constructor?</p>