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):給指定模組增加一個成員!不影響原檔案,只是在記憶體中增加