什么特殊方法?我是否应该在我的类中重新定义,以便它处理AttributeError
的异常,并在这些情况下返回一个特殊值?
例如,
>>> class MySpecialObject(AttributeErrorHandlingClass):
a = 5
b = 9
pass
>>>
>>> obj = MySpecialObject()
>>>
>>> obj.nonexistent
'special value'
>>> obj.a
5
>>> obj.b
9
我用谷歌搜索了一下答案,但没有找到。
发布于 2010-03-01 05:31:33
Otto Allmendinger提供的如何使用__getattr__
的示例使它的使用变得过于复杂。您只需定义所有其他属性,如果缺少一个属性,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-03-01 04:58:50
你有覆盖__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-03-01 04:58:15
我不清楚你的问题,但听起来你在寻找__getattr__
,可能还有__setattr__
和__delattr__
。
https://stackoverflow.com/questions/2352630
复制相似问题