python反射詳解

來源:互聯網
上載者:User

標籤:pytho   otf   print   輸入   報錯   not   module   lan   ima   

一、什麼是反射
反射就是通過字串的形式去對象(模組)中操作(尋找/擷取/刪除/添加)成員,一種基於字串的事件驅動

可使用反射的地方:

1、反射類中的變數 : 靜態屬性,類方法,靜態方法2、反射對象中的變數、對象屬性、普通方法3、 反射模組中的變數
4、反射本檔案中的變數
getattr(核心)

判斷類、對象或者模組中是否有相應的屬性或方法。用法:getattr(obj,str,default=None) 判斷obj中是否有str屬性,有就返回,沒有時有傳入第三參數就返回第三參數,沒有就報錯。

 class A:    name = ‘zs‘    age = 18print(getattr(A,‘name‘))print(getattr(A,‘language‘,‘notfound‘))

 

 settattr

設定屬性。第三參數為新的屬性值

class A:    name = ‘zs‘    age = 18setattr(A,‘name‘,‘ls‘)setattr(A,‘language‘,‘Chinese‘)print(getattr(A,‘name‘))print(getattr(A,‘language‘,‘notfound‘))

 

 

hasattr

判斷時候有某個屬性,有就返回True,沒有就返回False

class A:    name = ‘zs‘    age = 18if hasattr(A,‘name‘):    print(getattr(A,‘name‘))

 

delattr

刪除某個屬性

class A:    name = ‘zs‘    age = 18delattr(A,‘name‘)print(hasattr(A,‘name‘))

 

 反射本檔案

sys.modulses[__name__]就是本檔案對象。

import sysclass A:    def __repr__(self):        return ‘666‘if hasattr(sys.modules[__name__],‘A‘):    print(getattr(sys.modules[__name__],‘A‘)())

 

二、使用情境
input        使用者輸入的如果是a,那麼就列印1,如果輸入的是b就列印2    檔案        從檔案中讀出的字串,想轉換成變數的名字    網路        將網路傳輸的字串轉換成變數的名字

 

python反射詳解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.