Python: how to count the access of an instance variable
<p>I have a python class as below.</p>

<pre><code>class A(object):
   def __init__(self, logger):
       self.b = B()
       self.logger = logger
   def meth1(self):
       self.b.mymethod1()
   def meth2(self):
       self.meth1()
       self.b.mymethod2()
   .........
class B(object):
   ---------
</code></pre>

<p>How can I count how many time I accessed self.b variable on the invocation of meth2() or any method of class A. Is there any way, I can log the usage of self.b variable?</p>

<p>If you don't want to make a property, you can log the read/write access using <code>__getattribute__</code> (not <code>__getattr__</code> since <code>b</code> exists and would not be called) and <code>__setattr__</code>:</p>

<pre><code>class A(object):
   def __init__(self):
       # initialize counters first !
       self.b_read_counter = 0
       self.b_write_counter = 0
       # initialize b
       self.b = 12

   def __getattribute__(self,attrib):
      # log read usage
      if attrib=="b":
          self.b_read_counter+=1
      # now return b value
      return object.__getattribute__(self, attrib)

   def __setattr__(self,attrib,value):
      if attrib=="b":
          self.b_write_counter+=1

      return object.__setattr__(self, attrib,value)

a = A()

a.b = 23    # second write access (first is in the init method)
if a.b == 34:  # first read access
    print("OK")
if a.b == 34:
    print("OK")
if a.b == 34:  # third read access
    print("OK")
print(a.b_read_counter)
print(a.b_write_counter)
</code></pre>

<p>result:</p>

<pre><code>3
2
</code></pre>

python class