0、该写法错误,因为每当属性被赋值的时候,__setattr__()就会被调用,而里边的self.name=value+1语句又会再次调用__setattr__(),导致无限递归
1、__getattribute__(self,name)
2、位置1显示3
位置2显示2和None
3、
2
1
AttributeError
4、赋值时会调用__setattr__(),而__setattr__()重写中用到还未定义的属性值
0、
class demo:
def __getattr__(self,name):
return '该属性不存在'
>>> demo1 = demo()
>>> demo1.x
'该属性不存在'
>>>
1、
class demo:
def __getattr__(self,name):
self.name = 'FishC'
return self.name
>>> demo1 = demo()
>>> demo1.x
'FishC'
>>> demo.x = 'X-man'
>>> demo.x
'X-man'
>>>
2、
class Counter:#想办法取消赋值操作
def __init__(self):
super().__setattr__('count',0)
def __setattr__(self,name,value):
super().__setattr__('count',self.count + 1)
super().__setattr__(name,value)
def __delattr__(self,name):
super().__setattr__('count',self.count - 1)
super().__delattr__(name)
>>> c=Counter()
>>> c.x=1
>>> c.count
1
>>> c.y=1
>>> c.z=1
>>> c.count
3
>>> del c.x
>>> c.count
2