在 Python 中的装饰器中使用 setattr @classmethod好吗?



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

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)

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

我知道在类方法装饰器中,它调用类的原始初始化

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

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()

最新更新