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


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

 1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> hasattr(t, "name") #判斷對象有name屬性
 8 True
 9 >>> hasattr(t, "run")  #判斷對象有run方法
10 True
11 >>>

getattr(object, name[,default])
獲取對象object的屬性或者方法,如果存在打印出來,如果不存在,打印出默認值,默認值可選。
需要注意的是,如果是返回的對象的方法,返回的是方法的內存地址,如果需要運行這個方法,
可以在后面添加一對括號。

 1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> getattr(t, "name") #獲取name屬性,存在就打印出來。
 8 'xiaohua'
 9 >>> getattr(t, "run")  #獲取run方法,存在就打印出方法的內存地址。
10 <bound method test.run of <__main__.test instance at 0x0269C878>>
11 >>> getattr(t, "run")()  #獲取run方法,后面加括號可以將這個方法運行。
12 'HelloWord'
13 >>> getattr(t, "age")  #獲取一個不存在的屬性。
14 Traceback (most recent call last):
15   File "<stdin>", line 1, in <module>
16 AttributeError: test instance has no attribute 'age'
17 >>> getattr(t, "age","18")  #若屬性不存在,返回一個默認值。
18 '18'
19 >>>

 

setattr(object, name, values)
給對象的屬性賦值,若屬性不存在,先創建再賦值。

 1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> hasattr(t, "age")   #判斷屬性是否存在
 8 False
 9 >>> setattr(t, "age", "18")   #為屬相賦值,並沒有返回值
10 >>> hasattr(t, "age")    #屬性存在了
11 True
12 >>>

 

一種綜合的用法是:判斷一個對象的屬性是否存在,若不存在就添加該屬性。

 1 >>> class test():
 2 ...     name="xiaohua"
 3 ...     def run(self):
 4 ...             return "HelloWord"
 5 ...
 6 >>> t=test()
 7 >>> getattr(t, "age")    #age屬性不存在
 8 Traceback (most recent call last):
 9   File "<stdin>", line 1, in <module>
10 AttributeError: test instance has no attribute 'age'
11 >>> getattr(t, "age", setattr(t, "age", "18")) #age屬性不存在時,設置該屬性
12 '18'
13 >>> getattr(t, "age")  #可檢測設置成功
14 '18'
15 >>>

 

本文有參考其他博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM