What special method in Python handles AttributeError?
What special method(s?) should I redefine in my class so that it handled AttributeError
s exceptions and returned a special value in those cases?
For example,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9
I googled for the answer开发者_JS百科 but couldn't find it.
The example of how to use __getattr__
by Otto Allmendinger overcomplicates its use. You would simply define all the other attributes and—if one is missing—Python will fall back on __getattr__
.
Example:
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
You have do override __getattr__
, it works like this:
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'.
Your question isn't clear to me, but it sounds like you are looking for __getattr__
and possibly for __setattr__
, and __delattr__
.
精彩评论