问一个有关问题,有关_setattr_
问一个问题,有关__setattr__
验证执行结果:
>>> c = C()
Got it!
>>> c.__dict__
{'val': 10}
>>> c.ss
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'ss'
>>> c.ss = 2
Got it!
>>> c.__dict__
{'ss': 12, 'val': 10}
>>> c.me = 5
Got it!
>>> c.me
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'me'
>>> c.__dict__
{'ss': 12, 'val': 15}
>>> c.ss = 7
Got it!
>>> c.ss
17
>>> c.__dict__
{'ss': 17, 'val': 15}
>>> c.me = 90
Got it!
>>> c.__dict__
{'ss': 17, 'val': 100}
问题在于标红的部分,为什么c.me语句执行了__setattr__的else分支,
------解决方案--------------------
c.me是执行主分支,只不过执行self.val = value又嵌套调用__setattr__一次,为避免可能无限的嵌套,最好在这个函数里都是显式写法:
if name == 'me':
#self.val = value
self.__dict__[‘val'] = ...
------解决方案--------------------
你在__setattr__中第一行加入
class C(object):
def __init__(self):
self.val = 0
def __setattr__(self, name, value):
if name == 'me':
self.val = value
else:
self.__dict__[name] = value + 10
print 'Got it!'
验证执行结果:
>>> c = C()
Got it!
>>> c.__dict__
{'val': 10}
>>> c.ss
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'ss'
>>> c.ss = 2
Got it!
>>> c.__dict__
{'ss': 12, 'val': 10}
>>> c.me = 5
Got it!
>>> c.me
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'C' object has no attribute 'me'
>>> c.__dict__
{'ss': 12, 'val': 15}
>>> c.ss = 7
Got it!
>>> c.ss
17
>>> c.__dict__
{'ss': 17, 'val': 15}
>>> c.me = 90
Got it!
>>> c.__dict__
{'ss': 17, 'val': 100}
问题在于标红的部分,为什么c.me语句执行了__setattr__的else分支,
------解决方案--------------------
c.me是执行主分支,只不过执行self.val = value又嵌套调用__setattr__一次,为避免可能无限的嵌套,最好在这个函数里都是显式写法:
if name == 'me':
#self.val = value
self.__dict__[‘val'] = ...
------解决方案--------------------
你在__setattr__中第一行加入
print 'name = %s' % name