我应该在我的类中重新定义什么特殊方法,以便它处理
AttributeError
s 异常并在这些情况下返回一个特殊值?
例如,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9
我在谷歌上搜索了答案,但找不到。
您只需定义所有其他属性,如果缺少一个属性,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
你已经覆盖了
__getattr__
,它是这样工作的:
class Foo(object):
def __init__(self):
self.bar = 'bar'
def __getattr__(self, attr):
return 'special value'
foo = Foo()
foo.bar # calls Foo.__getattribute__() (defined by object), returns bar
foo.baz # calls Foo.__getattribute__(), throws AttributeError,
# then calls Foo.__getattr__() which returns 'special value'.
我不清楚你的问题,但听起来你正在寻找
__getattr__
,可能还有 __setattr__
和 __delattr__
.