python中反射(__import__和getattr使用)

反射:app

一、可經過字符串的形式導入模塊ide

  1.一、單層導入 函數

1 __import__('模塊名')
View Code

  1.二、多層導入spa

1 __import__(' list.text.commons',fromlist=True) #若是不加上fromlist=True,只會導入list目錄
View Code

二、能夠經過字符串的形式執行模塊的功能3d

 1 import glob,os
 2 
 3 modules = []
 4 for module_file in glob.glob("*-plugin.py"):
 5     try:
 6        module_name,ext = os.path.splitext(os.path.basename(module_file))
 7        module = __import__(module_name)
 8        modules.append(module)
 9     except ImportError:
10        pass #ignore broken modules
11     #say hello to all modules
12     for module in modules:
13        module.hello()
進行反射py代碼
1 def getfunctionbyname(module_name,function_name):
2     module = __import__(module_name)
3     return getattr(module,function_name)
__import__導入的模塊

三、反射即想到4個內置函數分別爲:getattr、hasattr、setattr、delattr  獲取成員、檢查成員、設置成員、刪除成員下面逐一介紹先看例子:code

 1 class Foo(object):
 2  
 3     def __init__(self):
 4         self.name = 'abc'
 5  
 6     def func(self):
 7         return 'ok'
 8  
 9 obj = Foo()
10 #獲取成員
11 ret = getattr(obj, 'func')#獲取的是個對象
12 r = ret()
13 print(r)
14 #檢查成員
15 ret = hasattr(obj,'func')#由於有func方法因此返回True
16 print(ret)
17 #設置成員
18 print(obj.name) #設置以前爲:abc
19 ret = setattr(obj,'name',19)
20 print(obj.name) #設置以後爲:19
21 #刪除成員
22 print(obj.name) #abc
23 delattr(obj,'name')
24 print(obj.name) #報錯
View Code
相關文章
相關標籤/搜索