3

我应该在我的类中重新定义什么特殊方法,以便它处理AttributeErrors 异常并在这些情况下返回一个特殊值?

例如,

>>> class MySpecialObject(AttributeErrorHandlingClass):
      a = 5
      b = 9
      pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9

我用谷歌搜索了答案,但找不到。

4

3 回答 3

6

__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
于 2010-02-28T21:31:33.190 回答
2

你已经做了 override __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'. 
于 2010-02-28T20:58:49.863 回答
1

您的问题我不清楚,但听起来您正在寻找__getattr__并且可能寻找__setattr__, 和__delattr__

于 2010-02-28T20:58:15.077 回答