开发者

What special method in Python handles AttributeError?

开发者 https://www.devze.com 2022-12-21 23:43 出处:网络
What special method(s?) should I redefine in my class so that it handled AttributeErrors exceptions and returned a special value in those cases?

What special method(s?) should I redefine in my class so that it handled AttributeErrors 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__.

0

精彩评论

暂无评论...
验证码 换一张
取 消