个人总结:使用setattr在实例对象初始化的时候添加属性,添加的属性值对该实例有效!
help 帮助
setattr(obj,key,value) # 添加属性
Help on built-in function setattr in module builtins:
setattr(obj, name, value, /)
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
getattr(obj,key[,default)# 获取属性
Help on built-in function getattr in module builtins:
getattr(...)
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent
to x.y.When a default argument is given, it is returned when the
attribute doesn'texist; without it, an exception is raised in that case.
Demo
class Demo():
...: def __init__(self,**kwargs):
...: if len(kwargs):
...: for key,value in kwargs.items():
...: setattr(self,key,value)
...: def get(self,key):
...: print(getattr(self,key))
运行
d1 = Demo()
In [41]: d2 = Demo(name="uu",age=19,gender="man")
In [42]: d2.get("age")
19
In [4]: d2.age
Out[4]: 19
In [5]: d2.name
Out[5]: 'uu'
In [6]: d1.name
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-6-b4b047799657> in <module>()
----> 1 d1.name
AttributeError: 'Demo' object has no attribute 'name'