python 內建函數setattr() getattr()

setattr(object,name,value):python

做用:設置object的名稱爲name(type:string)的屬性的屬性值爲value,屬性name能夠是已存在屬性也能夠是新屬性。code

getattr(object,name,default):get

做用:返回object的名稱爲name的屬性的屬性值,若是屬性name存在,則直接返回其屬性值;若是屬性name不存在,則觸發AttribetError異常或當可選參數default定義時返回default值。string

<!-- 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']
相關文章
相關標籤/搜索