1. 程式人生 > >python中反射(__import__和getattr使用)

python中反射(__import__和getattr使用)

反射:

1、可通過字串的形式匯入模組

  1.1、單層匯入 


 __import__('模組名')

  1.2、多層匯入

 __import__(' list.text.commons',fromlist=True) #如果不加上fromlist=True,只會匯入list目錄

2、可以通過字串的形式執行模組的功能


 import glob,os
 
 modules = []
 for module_file in glob.glob("*-plugin.py"):
     try:
        module_name,ext = os.path.splitext(os.path.basename(module_file))
        module = __import__(module_name)
        modules.append(module)
     except ImportError:
         pass
#ignore broken modules #say hello to all modules for module in modules: module.hello()
 
 def getfunctionbyname(module_name,function_name):
     module = __import__(module_name)
     return
getattr(module,function_name)

3、反射即想到4個內建函式分別為:getattr、hasattr、setattr、delattr  獲取成員、檢查成員、設定成員、刪除成員下面逐一介紹先看例子:


 
 class Foo(object):
 
     def __init__(self):
      self.name = 'abc'

    def func(self):
        return 'ok'
  
 obj = Foo()
 #獲取成員1 ret = getattr(obj, 'func')#獲取的是個物件
 r = ret()
 print(r)
 #檢查成員
 ret = hasattr(obj,'func')#因為有func方法所以返回True
 print(ret)
 #設定成員
 print(obj.name) #設定之前為:abc
 ret = setattr(obj,'name',19)
20 print(obj.name) #設定之後為:19
21 #刪除成員
22 print(obj.name) #abc
23 delattr(obj,'name')
24 print(obj.name) #報錯
   
   

1、可通過字串的形式匯入模組

  1.1、單層匯入 


 __import__('模組名')

  1.2、多層匯入

 __import__(' list.text.commons',fromlist=True) #如果不加上fromlist=True,只會匯入list目錄

2、可以通過字串的形式執行模組的功能


 import glob,os
 
 modules = []
 for module_file in glob.glob("*-plugin.py"):
     try:
        module_name,ext = os.path.splitext(os.path.basename(module_file))
        module = __import__(module_name)
        modules.append(module)
     except ImportError:
         pass #ignore broken modules
      #say hello to all modules
      for module in modules:
         module.hello()
 
 def getfunctionbyname(module_name,function_name):
     module = __import__(module_name)
     return getattr(module,function_name)

3、反射即想到4個內建函式分別為:getattr、hasattr、setattr、delattr  獲取成員、檢查成員、設定成員、刪除成員下面逐一介紹先看例子:


 
 class Foo(object):
 
     def __init__(self):
      self.name = 'abc'

    def func(self):
        return 'ok'
  
 obj = Foo()
 #獲取成員1 ret = getattr(obj, 'func')#獲取的是個物件
 r = ret()
 print(r)
 #檢查成員
 ret = hasattr(obj,'func')#因為有func方法所以返回True
 print(ret)
 #設定成員
 print(obj.name) #設定之前為:abc
 ret = setattr(obj,'name',19)
20 print(obj.name) #設定之後為:19
21 #刪除成員
22 print(obj.name) #abc
23 delattr(obj,'name')
24 print(obj.name) #報錯