我想覆盖我的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?
???
Run Code Online (Sandbox Code Playgroud)
什么代替问号?对于旧式类,答案很明显self.__dict__[name] = value,但文档表明这对于新式类来说是错误的.