python 内建函数setattr() getattr()
python 内建函数setattr() getattr()
setattr(object,name,value):
作用:设置object的名称为name(type:string)的属性的属性值为value,属性name可以是已存在属性也可以是新属性。
getattr(object,name,default):
作用:返回object的名称为name的属性的属性值,如果属性name存在,则直接返回其属性值;如果属性name不存在,则触发AttribetError异常或当可选参数default定义时返回default值。
<!-- lang: python -->
>>> class attribute():
... def __init__(self):
... self.attribute_1='i am attribute 1'
... self.attribute_2='i am attribute 2'
...
>>> result=attribute()
>>> dir(result)
['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2']
>>> getattr(result,'attribute_1')
'i am attribute 1'
>>> getattr(result,'attribute_3')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: attribute instance has no attribute 'attribute_3'
>>> getattr(result,'attribute_3','i am attribute 3')
'i am attribute 3'
>>> dir(result)
['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2']
>>> getattr(result,'attribute_2')
'i am attribute 2'
>>> setattr(result,'attribute_2','i am changed')
>>> getattr(result,'attribute_2')
'i am changed'
>>> setattr(result,'attribute_4','i am new one')
>>> dir(result)
['__doc__', '__init__', '__module__', 'attribute_1', 'attribute_2', 'attribute_4']