Manual
This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, ‘foobar’, 123) is equivalent to x.foobar = 123.
直译
该函数与getattr()相匹配,参数分别是一个对象、字符串和任意值。name字符串用来命名一个已存在的属性或一个新的属性,函数将value分配给属性,提供的object接受它。例如:setattr(x, ‘foobar’, 123)等同于x.foobar = 123。
实例
>>> class 优快云:
def __init__(self):
self.foobar = '优快云er'
>>> a = 优快云()
>>> a.foobar
'优快云er'
>>> setattr(a, 'foobar', 'Hello')
>>> a.foobar
'Hello'
>>> setattr(a, 'foo', 'world!')
>>> a.foo
'world!'