Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to count the access of an instance variable

Tags:

python

class

I have a python class as below.

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):
   ---------

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?

like image 896
lima Avatar asked Nov 07 '25 22:11

lima


1 Answers

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

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)

result:

3
2
like image 84
Jean-François Fabre Avatar answered Nov 09 '25 17:11

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!