在 class 方法中使用 setattr 对自己进行选择

using setattr within a class method to sel something on self

这样做的时候

class Example:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def update(self, **kwargs):
        for key, value in kwargs.items():
            getattr(self, key)
            setattr(self, key, value)

.. 更新函数不会更新此 class 的实例。我已经尝试了 self.__setattr__(key, value)object.__setattr__(self, key, value),甚至尝试了 eval(f"self.{key}={repr(value)}") 却抛出了错误!

更新:代码确实 work.initially 我已经编码 self.__setattr__(key, value)。 Microsoft vscode(运行 on linux)以某种方式缓存了很长一段时间的东西,尽管通过几次代码更改轮换并没有显示测试结果有任何变化我是运行。休息一下问这个问题后,我 运行 下面的答案代码,然后恢复到 setattr,一切都从那里开始。真的很生气!!

使用__dict__作为快捷方式:

class Example:
    def __init__(self, a, b):
        self.a = a
        self.b = b

    def update(self, **kwargs):
        # you need to do some checks here (if attribute exists or not)
        self.__dict__.update(kwargs)


e = Example(1, 2)
print(e.__dict__)

e.update(a=3, b=4)
print(e.__dict__)

输出:

{'a': 1, 'b': 2}
{'a': 3, 'b': 4}