1. 程式人生 > 其它 >Python的hasattr() getattr() setattr() 函式使用方法詳解

Python的hasattr() getattr() setattr() 函式使用方法詳解

hasattr(object, name) 判斷一個物件裡面是否有name屬性或者name方法,返回BOOL值,有name特性返回True, 否則返回False。 需要注意的是name要用括號括起來

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> hasattr(t, "name") #判斷物件有name屬性
True
>>> hasattr(t, "run")  #判斷物件有run方法
True
>>>

getattr(object, name[,default]) 獲取物件object的屬性或者方法,如果存在打印出來,如果不存在,打印出預設值,預設值可選。 需要注意的是,如果是返回的物件的方法,返回的是方法的記憶體地址,如果需要執行這個方法, 可以在後面新增一對括號。

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> getattr(t, "name") #獲取name屬性,存在就打印出來。
'xiaohua'
>>> getattr(t, "run")  #獲取run方法,存在就打印出方法的記憶體地址。
<bound method test.run of <__main__.test instance at 0x0269C878>>
>>> getattr(t, "run")()  #獲取run方法,後面加括號可以將這個方法執行。
'HelloWord'
>>> getattr(t, "age")  #獲取一個不存在的屬性。
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age","18")  #若屬性不存在,返回一個預設值。
'18'
>>>

 setattr(object, name, values) 給物件的屬性賦值,若屬性不存在,先建立再賦值。

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> hasattr(t, "age")   #判斷屬性是否存在
False
>>> setattr(t, "age", "18")   #為屬相賦值,並沒有返回值
>>> hasattr(t, "age")    #屬性存在了
True
>>>

一種綜合的用法是:判斷一個物件的屬性是否存在,若不存在就新增該屬性。

>>> class test():
...     name="xiaohua"
...     def run(self):
...             return "HelloWord"
...
>>> t=test()
>>> getattr(t, "age")    #age屬性不存在
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: test instance has no attribute 'age'
>>> getattr(t, "age", setattr(t, "age", "18")) #age屬性不存在時,設定該屬性
'18'
>>> getattr(t, "age")  #可檢測設定成功
'18'
>>>

作者:岑宇 出處:http://www.cnblogs.com/cenyu/ 本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段宣告,且在文章頁面明顯位置給出原文連線,否則保留追究法律責任的權利。  如果文中有什麼錯誤,歡迎指出。以免更多的人被誤導。