Python高手之路【十】python基礎之反射,python之路

來源:互聯網
上載者:User

Python高手之路【十】python基礎之反射,python之路

反射說簡單點 --> 就是利用字串的形式去對象(模組)中操作(尋找/檢查/刪除/設定)成員。

 

需求:由使用者輸入一個模組名,使用者輸入什麼模組名,檔案中就匯入什麼模組:

1:檔案都在同一目錄下的匯入

在同一目錄下建立兩個檔案,index.py , commons.py

commons.py檔案內容如下:

 

def f1():    return "F1"def f2():    return 'f2'

 

在index.py檔案中書寫代碼:

m = input('input module : ')module = __import__(m)#module相當於import modulename as f形式中的別名print(module.f1())

使用 __import__('模組名')的方式匯入模組!為什麼要使用這種方式匯入模組,而不使用 import modulename方式匯入呢?因為使用者輸入進來的都是字串,而import modulename方式,modulename不是一個字串!

此時執行index.py檔案,就能正常匯入模組,接收f1函數中的傳回值:

 

需求:上面已經實現使用者輸入模組名就匯入哪個模組,現在要求由使用者再輸入函數名,然後檔案中就執行該模組中的對應的函數

m = input('input module : ')#使用者輸入模組名f = input('input func name : ')#使用者輸入函數名module = __import__(m)#匯入使用者輸入的模組func = getattr(module,f)#調用使用者輸入的函數print(func())

 

如果commons模組與index.py檔案不在同一目錄的匯入:假如commons.py檔案在lib/commons.py下

module = __import__('lib.'+m,fromlist=True)#匯入使用者輸入的模組
附錄:

getattr(object,name) :擷取指定模組中的指定成員

hasattr(object,name):判斷指定模組中是否存在指定成員

delattr(object,name):刪除指定模組中的指定成員!不影響原檔案,只是在記憶體中刪除

setattr(object,name,value):給指定模組增加一個成員!不影響原檔案,只是在記憶體中增加

 

聯繫我們

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