setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
getattr()用法详见博文:python中getattr()函数用法详解_IT之一小佬的博客-CSDN博客
setattr() 函数源码:
def setattr(x, y, v): # real signature unknown; restored from __doc__
"""
Sets the named attribute on the given object to the specified value.
setattr(x, 'y', v) is equivalent to ``x.y = v''
"""
pass
语法结构:
setattr(object, name, value)
示例代码1: 【类中属性值存在的情况】
class Test(object):
test = 1
print(Test.test)
print(Test().test)
obj = Test()
ret = getattr(obj, 'test') # 获取属性 test 值
print(ret)
setattr(obj, 'test', 5) # 设置属性 test 值
print(obj.test)
运行结果:
示例代码2: 【类中属性值不存在的情况】
class Test(object):
test = 1
obj = Test()
setattr(obj, 'age', 5) # 设置属性 age 值
print(obj.age)
运行结果:
示例代码3: 【setattr和getattr共同使用,嵌套数据结构类型】
class Struct(object):
def __init__(self, data):
for name, value in data.items():
setattr(self, name, self._wrap(value))
def _wrap(self, value):
if isinstance(value, (tuple, list, set, frozenset)):
return type(value)([self._wrap(v) for v in value])
else:
return Struct(value) if isinstance(value, dict) else value
d = {'a': 1, 'b': {'c': 2}, 'd': ["AA", {'BB': "CC"}]}
x = Struct(d)
print(x)
setattr(x, "XX", {})
print(x.__dict__)
print(type(x))
setattr(getattr(x, 'b'), 'cc', {'name': 'dgw'})
setattr(getattr(x, 'b'), 'ccc', [1, 2, 3])
print(x.__dict__)
print(x.b.c)
print(x.b.cc)
print(x.b.ccc)
运行结果: