【Python】hasattr() getattr() setattr() 使用方法詳解

來源:互聯網
上載者:User

標籤:擷取對象   記憶體   注意   括弧   blog   com   span   att   self   

本文轉自 https://www.cnblogs.com/cenyu/p/5713686.html

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 True11 >>>

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 True12 >>>

 

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

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

 

【Python】hasattr() getattr() setattr() 使用方法詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.