方式1 - 反射
hasattr 方法
判斷當前實例中是否有着字符串能映射到的屬性或者方法, 一般會在 getattr 之前作為判斷防止報錯
getattr 方法
獲取到當前實例中傳入字符串映射到的屬性或者方法
示例
class A(object): def run(self): return "run" a = A() print hasattr(a, "run") # True print getattr(a, "run") # <bound method A.run of <__main__.A object at 0x0000000002A57160>> print getattr(a, "run")() # run
方式2 - operator 模塊
methodcaller 方法
參數
傳入兩個參數, 分別為字符串表示映射的方法, 另一個參數為此方法的運行參數,
返回值
返回一個 字符串映射到的方法實例
示例
import operator class A(object): def run(self): return "run" def eat(self, s): return s + ": eat" a = A() print operator.methodcaller("run") # <operator.methodcaller object at 0x0000000002ADAC08> print operator.methodcaller("run")(a) # run print operator.methodcaller("eat", "yangtuo")(a) # yangtuo: eat