python - 在 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。
解决方案
从提供的示例来看,您似乎没有任何理由需要在类范围内设置变量。如果该假设是正确的,那么简单的解决方案是直接设置字典项(并在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()
推荐阅读
- python - 在原始方法调用之后提取方法并插入调用
- linux - 如何在 Airflow 中构建和上传 Docker 镜像?
- tcl - 调用“expect eof”时,预期脚本因“spawn id not open”而失败
- flutter - Flutter ObjectBox - 如何进行单元测试?
- outlook - 如果主题相同,Outlook 规则不会根据类别发送电子邮件
- reactjs - 使用 TypeScript 在 React 组件上强制执行属性
- assembly - 如何在 MASM 中使用 EXTERN?
- java - 我如何退出这个while循环
- excel - VBA 在自动创建的工作簿中为工作表命名
- angular - Ngrx 状态可变性