title: python 3.8 - dynamically set properties to a class when it's initialized
body: <p>I'm trying to create a class whose instances can have an arbitrary number of attributes. This can be easily achieved using <code>**kwargs</code> in the <strong><strong>init</strong></strong> method. Then, for each of its attributes I need to count the access throughout the entire lifecycle of an instance.</p>
  <p>If I had a <em>property</em> for each attributes, then I could increment a counter in both <em>getter</em> and <em>setter</em> methods for that attribute accessed at a given time.</p>
  <p>The problem is that I need to create those properties dynamically, because I don't know which attributes an instance of my class will have.</p>
  <p>I'm sure this can be solved by mean of <code>metaclasses</code>. Although, I'm trying to address that <strong>without</strong> them.</p>
  <p>I've written this code so far:</p>
  <pre><code>class CountAttr:
  
      def __init__(self, **kwargs):
          # here I init the counter for each keyword argument
          self.__count = {attr: 0 for attr in kwargs}
          # then I add the attribute to my instance
          for kwarg in kwargs:
              object.__setattr__(self, '_' + kwarg, kwargs[kwarg])
              def getter(self):
                  self.__count[kwarg] +=1
                  return object.__getattribute__(self, '_' + kwarg)
              def setter(self, value):
                  self.__count[kwarg] +=1
                  object.__setattr__(self, '_' + kwarg, kwargs[kwarg], value)
              #here comes the issue: the property doesn't work
              object.__setattr__(self, kwarg, property(getter, setter))
  
      @property
      def count(self):
          return self.__count
  
  test = CountAttr(x=5, y=6)
  
  print(test.x, test.y)
  </code></pre>
  <p>Debugging my code, I've assessed that <code>test</code> has attribute <code>_x</code> with value of <code>5</code>, as well as attribute <code>_y</code> with value of <code>6</code>. <code>x</code> and <code>y</code> are shown as <code>property objects</code>, so everything seems to work fine. But it doesn't at the end.</p>
  <p>Indeed, the final print statement will output this:</p>
  <p><code>&lt;property object at 0x7fbb241d4b30&gt; &lt;property object at 0x7fbb241d4b80&gt;</code></p>
  <p>While the output I'm expecting is: <code>5 6</code>, that is, the value of <code>_x</code> and <code>_y</code> attributes.</p>