反射:
1、可通過字符串的形式導入模塊
1.1、單層導入

1 __import__('模塊名')
1.2、多層導入

1 __import__(' list.text.commons',fromlist=True) #如果不加上fromlist=True,只會導入list目錄
2、可以通過字符串的形式執行模塊的功能

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()

1 def getfunctionbyname(module_name,function_name): 2 module = __import__(module_name) 3 return getattr(module,function_name)
3、反射即想到4個內置函數分別為:getattr、hasattr、setattr、delattr 獲取成員、檢查成員、設置成員、刪除成員下面逐一介紹先看例子:

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) #報錯