我想覆盖我的 Python 类的 __getattribute__
和 __setattr__
方法。我的用例是常见的:我有一些我想要处理的特殊名称,我想要其他任何东西的默认行为。对于 __getattribute__
,似乎我可以通过提高 AttributeError
来请求默认行为。但是,我怎样才能在 __setattr__
中实现相同的目标?这是一个简单的例子,实现了一个具有不可变字段“A”、“B”和“C”的类。
class ABCImmutable(SomeSuperclass):
def __getattribute__(self, name):
if name in ("A", "B", "C"):
return "Immutable value of %s" % name
else:
# This should trigger the default behavior for any other
# attribute name.
raise AttributeError()
def __setattr__(self, name, value):
if name in ("A", "B", "C"):
raise AttributeError("%s is an immutable attribute.")
else:
# How do I request the default behavior?
???
用什么代替问号?对于旧式类,答案显然是 self.__dict__[name] = value
,但文档表明这对于新式类是错误的。
原文由 Ryan C. Thompson 发布,翻译遵循 CC BY-SA 4.0 许可协议
它是
在 Python 2 中,或者
在 Python 3 中。
此外,提高
AttributeError
并不是 您退回到__getattribute__
的默认行为的方式。你回退到默认值在 Python 2 或
在 Python 3 上。
Raising
AttributeError
the default handling and goes to__getattr__
, or just produces anAttributeError
in the calling code if there’s no__getattr__
.请参阅有关 自定义属性访问 的文档。