bod*_*ydo 3 python attributeerror
我应该在我的类中重新定义什么特殊方法,以便它处理AttributeError异常并在这些情况下返回一个特殊值?
例如,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9
Run Code Online (Sandbox Code Playgroud)
我用谷歌搜索答案,但找不到。
__getattr__Otto Allmendinger的如何使用的示例使其使用过于复杂。您只需定义所有其他属性,如果缺少一个属性,Python 将依靠__getattr__.
例子:
class C(object):
def __init__(self):
self.foo = "hi"
self.bar = "mom"
def __getattr__(self, attr):
return "hello world"
c = C()
print c.foo # hi
print c.bar # mom
print c.baz # hello world
print c.qux # hello world
Run Code Online (Sandbox Code Playgroud)