Python之動態調用函數
在Java中,動態調用可通過反射機制實現。Python中,也可通過__import__(filename) + getattr()實現。
1、__import__(filename):動態加載
python中,一般通過from XX import XX引入模塊,當調用模塊不確定時,可通過__import__()動態載入,通過“字符串”函數名動態調用函數。
def __import__(name, globals=None, locals=None, fromlist=(), level=0): # real signature unknown; restored from __doc__
"""
__import__(name, globals=None, locals=None, fromlist=(), level=0) -> module
Import a module. Because this function is meant for use by the Python
interpreter and not for general use it is better to use
importlib.import_module() to programmatically import a module.
The globals argument is only used to determine the context;
they are not modified. The locals argument is unused. The fromlist
should be a list of names to emulate ``from name import ...'', or an
empty list to emulate ``import name''.
When importing a module from a package, note that __import__('A.B', ...)
returns package A when fromlist is empty, but its submodule B when
fromlist is not empty. Level is used to determine whether to perform
absolute or relative imports. 0 is absolute while a positive number
is the number of parent directories to search relative to the current module.
"""
pass
name: 模塊名
2、getattr() :返回一個對象屬性值
def getattr(object, name, default=None): # known special case of getattr
"""
getattr(object, name[, default]) -> value
Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
When a default argument is given, it is returned when the attribute doesn't
exist; without it, an exception is raised in that case.
"""
pass
object:對象屬性的值
name: 類屬性名對應的字符串
default: name對應屬性不存在,給定default參數則返回default,沒有default,則直接有AttributeError異常
3、例子
動態引入運行:#1 動態載入模塊 ;#2 獲取類對象; #3 獲取函數對象,func(para_comm) 動態調用函數。
注:
載入模塊時,會碰見"No module named XXX" , 注意path搜索模塊路徑的配置。
獲取對象時,也可通過 hasattr(calssname, attributename) 判斷屬性是否存在, 避免AttributeError的異常。
import_module = __import__(moudlename) # 1
b = getattr(import_module, classname)() # 2
func = getattr(b, methodname) # 3
res = func(para_comm) # para_comm 傳入參數