首页 > 解决方案 > 在 Python 的 @classmethod 装饰器中使用 setattr 好不好

问题描述

我编写了一个类,该类从具有不同输入参数的几个函数中调用。

class demo:   
     def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar
     @classmethod
     def fromdict(cls, dict):
        for key, val in dict.values():
            setattr(cls, key, val)
        return cls(foo1, bar1)

实例化类有两种方法。在第一种方法中,我可以控制属性名称。而在第二种情况下,我事先不知道名字。在我们执行某些操作之前,有没有办法获取名称。或者有没有办法知道使用哪种方法来实例化类。

我知道在 classmethod 装饰器中它调用了类的原始init

标签: pythonpython-3.x

解决方案


从提供的示例来看,您似乎没有任何理由需要在类范围内设置变量。如果该假设是正确的,那么简单的解决方案是直接设置字典项(并在init中使用可选的 kwargs )。

class demo:   
 def __init__(self, foo=None, bar=None):
    self.foo = foo
    self.bar = bar

 @classmethod
 def fromdict(cls, dct):
    # create instance
    obj = cls()
    # vars grants direct access to the underlying __dict__
    # so you can arbitrarily assign new variables
    return vars(obj).update(dct)

然而,这个问题并不完全清楚,所以请更具体地说明你想要实现的目标,我会更新。

小提示:避免dict用作变量名,因为它是 python 中的内置类型。调用 dict() 创建一个字典。

另外,在你的 for 循环中:

for key, val in dict.values()

你在这里想要的是for key, val in dct.items()


推荐阅读