Python中的哪个特殊方法处理AttributeError?
我应该在我的类中重新定义哪些特殊方法,以便处理AttributeError
异常,并在这种情况下返回一个特殊的值呢?
举个例子,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9
我在网上搜索了答案,但没找到。
3 个回答
1
我不太明白你的问题,但听起来你是在寻找 __getattr__
,可能还想了解 __setattr__
和 __delattr__
。
3
你需要重写一下 __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'.
8
你只需要定义其他所有的属性,如果有一个缺失了,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