Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:如何计算实例变量的访问权限_Python_Class - Fatal编程技术网

Python:如何计算实例变量的访问权限

Python:如何计算实例变量的访问权限,python,class,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(obje

我有一个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变量的使用情况?

您可以使用它,或者只创建一个基本上是描述符的属性

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

将“b”设为属性,并增加对应于setter中的计数器

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

在您的类中,用_b

替换b,您可以使用属性,例如:

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
  ...
  ...

如果不想创建属性,可以使用
\uuuuuuGetAttribute\uuuuuuuuuu
(不是
\uuuuuuuuu getattr\uuuuuuuuu
,因为
b
存在并且不会被调用)和
\uuuuuuuuuuuuuuuuuuuuuuuuuuu setattr\uuuuuu

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

谢谢这正是我想要的。使用属性是一个好主意,但我还是会选择getattribute answer,因为它可以处理实例变量和实例方法。谢谢