Python中的反射與動態匯入

2021-08-22 09:58:41 字數 1084 閱讀 3732

反射:利用字串的形式在物件(模組)中操作成員

匯入模組為commcons,可執行檔案為test在同一檔案中,如下:

hasattr():用於判斷物件是否包含對應的屬性,包含返回true,不包含則返回false。

getattr():返回乙個物件的屬性

getattr(object,name,[default])    object--物件  name -- 字串,物件屬性。default--預設值,

import commons #匯入commons模組

#次函式在test檔案中

def main():

func_name = input("請輸入模組名稱:")

if hasattr(commons,func_name): #判斷是否有這個方法

func = getattr(commons,func_name)

func()

動態匯入需要呼叫importlib,importlib模組支援傳遞字串來匯入模組。用到的方法:importlib.import_module()

#動態匯入 

import importlib #呼叫importlib模組

module = 'commons'

#module = 'src.commons' --如果commons和test不在同一目下如在src下(從src模組中匯入commons.py)

func_name = 'remind'

m = importlic.import_module(module) #對模組進行匯入

func = getattr(m,func_name) #利用反射呼叫物件m中的屬性func_name

func()

Python隨心記 反射 動態匯入模組

hasatttr object,name 檢測物件中是否存在name屬性 getattr object,name,delault null setattr object,x,true delattr object,x 刪除屬性class blackmedium feture ugly def ini...

python 反射 python中的反射

什麼是反射?有時我們要訪問某個變數或是方法時並不知道到底有沒有這個變數或方法,所以就要做些判斷。判斷是否存在字串對應的變數及方法。我們知道訪問變數時是不能加引號的,否則會被當成字串處理。如果要通過字串找到對應的變數,那該怎麼辦呢 反射就是用於解決上面兩個問題而產生的,所謂反射,按我的理解就是反過來告...

python之路(9)反射 包裝類 動態模組匯入

目錄 python提供自省的四個方法 hasattr object,name 判斷object中有沒有有個name字串對應對應的方法和屬性 class demo name chen age 22 def test func self print 存在 hasattr demo,test func t...