1、与属性访问有关的魔法方法
__getattr__(self,name)
定义当用户试图获取某一不存在的属性时的行为
__getattribute__(self,name)
定义当该类属性被访问时的行为
__setattr__(self,name,value)
定义一个属性被设置时的行为
__delattr__(self,name)
定义一个属性被删除时的行为
注意:
def __setattr__(self, name, value): self.name = value + 1 #此代码试图在对对象的属性进行赋值时让属性的值加1但是 self.name = value + 1这句又会触发 __setattr__从而导致无限递归
正确写法:
def __setattr__(self, name, value): super().__setattr__(name,value+1) #寻找父类的__setattr__方法来对属性name赋值
或者:
def __setattr__(self, name, value): self.__dict__[name] = value + 1
以下的代码问题:
class Counter: def __init__(self): self.counter = 0 # 这里会触发 __setattr__ 调用 def __setattr__(self, name, value): self.counter += 1 “””既然需要 __setattr__ 调用后才能真正设置 self.counter 的值,所以这时候 self.counter 还没有定义,所以没法 += 1,错误的根源。””” super().__setattr__(name, value) def __delattr__(self, name): self.counter -= 1 super().__delattr__(name)
定义一个count类实现检测属性的增减
class Counter: def __init__(self): self.counter = 0 def __setattr__(self, name, value): if name== ‘counter‘: super().__setattr__(name, value) else: self.counter += 1 super().__setattr__(name, value) def __delattr__(self, name): if name ==‘counter‘: super().__delattr__(name) else: self.counter -= 1 super().__delattr__(name)
class Counter: def __init__(self): super().__setattr__(‘counter‘, 0) def __setattr__(self, name, value): super().__setattr__(‘counter‘, self.counter + 1) super().__setattr__(name, value) def __delattr__(self, name): super().__setattr__(‘counter‘, self.counter - 1) super().__delattr__(name)
原文地址:https://www.cnblogs.com/PythonFCG/p/8436637.html
时间: 2024-10-07 14:56:56