python 經過 實例方法 名字的字符串調用方法

方式1 - 反射 

hasattr 方法

判斷當前實例中是否有着字符串能映射到的屬性或者方法, 通常會在  getattr 以前做爲判斷防止報錯spa

getattr 方法

獲取到當前實例中傳入字符串映射到的屬性或者方法code

示例

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 方法

參數

傳入兩個參數, 分別爲字符串表示映射的方法, 另外一個參數爲此方法的運行參數,blog

返回值

返回一個 字符串映射到的方法實例字符串

示例

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
相關文章
相關標籤/搜索