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


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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM