相关疑难解决方法(0)

如何在Python中的新样式类上正确覆盖__setattr__和__getattribute__?

我想覆盖我的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,但文档表明这对于新式类来说是错误的.

python inheritance python-2.x setattr python-3.x

38
推荐指数
2
解决办法
3万
查看次数

标签 统计

inheritance ×1

python ×1

python-2.x ×1

python-3.x ×1

setattr ×1