首页 > 解决方案 > __setattr__ 未检测到 .append() 更改

问题描述

所以我正在创建一个可以锁定值(使它们不可编辑)的可继承类,在它所使用的类中,它工作正常,除非属性被锁定并附加到它。由于某种原因setattr没有拿起 .append() ,老实说我不确定如何检测/停止它,有人可以帮助我吗?

我的代码如下:

class valuelocker:

    def __getattribute__(self, name):
        return object.__getattribute__(self, name)

    def __setattr__(self, name, value):

        # Prevents manual changes to the __locked__ attribute
        if name == "__locked__":
            for attr in self.__locked__:
                if attr not in value:
                    raise Exception("locked attribute cannot be removed")
                elif self.__locked__[attr] != value[attr]:
                    raise Exception("locked attribute cannot be changed")
        # Prevents locked attributes from being changed
        elif name in self.__locked__:
            raise Exception("locked attribute cannot be changed")

        # Changes the value of an attribute 
        object.__setattr__(self, name, value)
        if name != "__dict__":
            self.__dict__[name] = value

    # Adds an attribute to the __locked__ attibute
    def lock(self, name):
        self.__locked__[name] = eval(f"self.{name}")

    __locked__ = {}

class test(valuelocker):
    List = []

t = test()
t.lock("List")

# Works for some reason (it's not doing what it's supposed to)
t.List.append(None)

# Doesn't work (it's doing what it's supposed to)
t.List = [None]

标签: pythonpython-3.x

解决方案


推荐阅读