有一个场景就是我们 给你一个list 批量把里面的值 赋给类里,如何做呢, 请看代码:
test=["a","b","c"] // 指定需要添加的属性名
req={"a":1,"b":2,"c":3,“d”:4} //指定data
Depence = type("Depence",(),{}) //创建类
for i in test:
setattr(Depence,i,eval(str(req))[i]) // 利用setattr 遍历添加属性
print(Depence.__dict__)
打印的结果为:
{'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Depence' objects>, '__weakref__': <attribute '__weakref__' of 'Depence' objects>, '__doc__': None, 'a': 1, 'b': 2, 'c': 3}
成功了, perfect !!!!