python--反射機制

來源:互聯網
上載者:User

標籤:find   att   模組名   一個   name   利用   linux   pre   font   

  python的反射機制能夠讓我們利用字串去動態驅動不同的事件,例如匯入模組,調用函數等,涉及到的函數有hasattr,getattr,setattr,delattr

  • hasattr:檢查模組或者對象中是否有某個成員
  • getattr:擷取成員,即將字串輸入的資料裝換成對應的成員
  • setattr:設定成員
  • delattr:刪除成員  
 1 modName=input("請輸入模組名:") 2 #__import__:根據字串輸入的模組名匯入相對應得模組,如果有嵌套的模組,需要加fromlist=True 3 name=__import__(‘se.‘+modName,fromlist=True) 4  5 print(modName) 6  7 funcName=input("請輸入函數名:") 8  9 #檢查模組中是否相對應得函數10 exis=hasattr(name,funcName)11 12 if exis:13     #獲得函數14     fun=getattr(name,funcName)15     #執行函數16     fun()17     #獲得變數18     value=getattr(name,"PYTHON")19     print(value)20 else:21     print("not find")22 23 #設定24 setattr(name,"NAME","LINUX")25 print(hasattr(name,"NAME"))26 #刪除27 delattr(name,"PYTHON")28 print(hasattr(name,"PYTHON"))
反射
 1 modName=input("請輸入模組名:") 2 #__import__:根據字串輸入的模組名匯入相對應得模組,如果有嵌套的模組,需要加fromlist=True 3 name=__import__(‘se.‘+modName,fromlist=True) 4  5 className=input("請輸入類名:") 6 #將模組中的類匯入 7 cls=getattr(name,className) 8 #建立該類的一個執行個體 9 clsObj=cls()10 #添加該對象的一個欄位11 clsObj.PYTHON="sdfsfdsf"12 funcName=input("請輸入函數名:")13 14 #檢查類中是否相對應得函數15 exis=hasattr(clsObj,funcName)16 17 if exis:18     #獲得該對象的函數19     fun=getattr(clsObj,funcName)20     #執行該對象的函數21     fun()22     #獲得該對象的變數23     value=getattr(clsObj,"PYTHON")24     print(value)25 else:26     print("not find")27 28 #設定29 setattr(clsObj,"NAME","LINUX")30 print(hasattr(clsObj,"NAME"))31 #刪除該對象相對應的變數,如果該變數是屬於類的,那麼就會出錯32 delattr(clsObj,"PYTHON")33 print(hasattr(clsObj,"PYTHON"))
反射二

 

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.