Python:如何计算实例变量

时间:2016-09-23 09:27:45

标签: python class

我有一个python类,如下所示。

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

我如何计算在调用meth2()或类A的任何方法时访问self.b变量的次数。有没有办法,我可以记录self.b变量的用法吗?

4 个答案:

答案 0 :(得分:2)

使'b'成为属性,并增加对应于setter中的计数器。

@property
def b(self):
  self.b_counter += 1
  return self._b

并在您的班级中用_b

替换b

答案 1 :(得分:1)

您可以使用descriptors或仅创建一个基本上是描述符的属性。

class A(object):
   def __init__(self, logger):
       self._b = B()
       self._b_counter = 0
       self.logger = logger

   @property
   def b(self):
       self._b_counter += 1
       return self._b

   def meth1(self):
       self.b.mymethod1()

   def meth2(self):
       self.meth1()
       self.b.mymethod2()

答案 2 :(得分:1)

如果您不想创建属性,则可以使用__getattribute__(而不是__getattr__来记录读/写访问权限,因为b存在并且不会被调用)和__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)

结果:

3
2

答案 3 :(得分:0)

您可以使用属性,如:

class A(object):
  def __init__(self, logger):
      self._b = B()
      self._count = 0
      self.logger = logger

  @property
  def b(self):
     self._count += 1
     return self._b
  ...
  ...