Python中有什么特殊的方法来处理AttributeError?

问题描述 投票:0回答:3

我应该在我的类中重新定义什么特殊方法,以便它处理

AttributeError
s 异常并在这些情况下返回一个特殊值?

例如,

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

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

python attributeerror
3个回答
7
投票

您只需定义所有其他属性,如果缺少一个属性,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

2
投票

你已经覆盖了

__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'. 

1
投票

我不清楚你的问题,但听起来你正在寻找

__getattr__
,可能还有
__setattr__
__delattr__
.

© www.soinside.com 2019 - 2024. All rights reserved.