>>> class T:
def __init__(self, obj):
self.obj = obj # 这里也会调用 __setattr__ 方法
def __getattr__(self, name):
try:
return self.obj[name] # 以 obj 中的值来代替
except KeyError:
raise AttributeError("'T' object has no attribute '%s'" %name)
def __getattribute__(self, name):
return super().__getattribute__(name) # 避免无穷递归
def __setattr__(self, name, value):
print('setting attribute', name)
if name != 'obj' and not isinstance(value, int): # “obj”属性不是整数,需要排除
raise TypeError("value need to be an integer.")
super().__setattr__(name, value) # 避免无穷递归
运行结果:
>>> t = T({'key': 'vvv', 'aa': 'b'})
setting attribute obj
>>>
>>> t.__dict__
{'obj': {'key': 'vvv', 'aa': 'b'}}
>>> t.a # 这里因为属性“a”也不在属性“obj”中
Traceback (most recent call last):
File "", line 6, in __getattr__
return self.obj[name]
KeyError: 'a'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "", line 1, in
t.a
File "", line 8, in __getattr__
raise AttributeError("'T' object has no attribute '%s'" %name)
AttributeError: 'T' object has no attribute 'a'
>>> t.aa # aa 在 obj 中
'b'
>>> t.x = 'aaa'
setting attribute x
Traceback (most recent call last):
File "", line 1, in
t.x = 'aaa'
File "", line 11, in __setattr__
raise TypeError("value need to be an integer.")
TypeError: value need to be an integer.
>>>
>>> t.x = 13
setting attribute x
>>>
>>> t.__dict__
{'obj': {'key': 'vvv', 'aa': 'b'}, 'x': 13}
>>>
分享到:
2017-07-31 10:48
浏览 116
评论