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']