[Python] 動態函數調用(通過函數名)

來源:互聯網
上載者:User

標籤:color   only   com   states   name   class   sign   unknown   icm   

2018-04-09 update

利用python中的內建函數 eval() ,函數說明:

def eval(*args, **kwargs): # real signature unknown    """    Evaluate the given source in the context of globals and locals.        The source may be a string representing a Python expression    or a code object as returned by compile().    The globals must be a dictionary and locals can be any mapping,    defaulting to the current globals and locals.    If only globals is given, locals defaults to it.    """    pass

 

範例1:

def function2(name, age):    print("name: %s, age: %s" % (name, age))if __name__ == ‘__main__‘:    eval("function2")("Alice", 11)    # 或者:    args = ["Alice", 11]    kwargs = {}    eval("function2")(*args, **kwargs)    """    輸出結果都是:    name: Alice, age: 11    """

 

範例2:

class Test(object):    states = [u"大於等於零", u"大於等於二"]    state2function = {u"大於等於零": "check_gt0", u"大於等於二": "check_gt2"}    @staticmethod    def check_gt0(x):        return x >= 0    @staticmethod    def check_gt2(x):        return x >= 2    def predict(self, x):        for state in Test.states:            check_ans = eval("Test." + Test.state2function[state])(x)  # 調用Test類中的方法            print(state, Test.state2function[state], x, check_ans)if __name__ == ‘__main__‘:    test = Test()    test.predict(x=-1)    test.predict(x=1)    test.predict(x=2)    """    輸出:    大於等於零 check_gt0 -1 False    大於等於二 check_gt2 -1 False    大於等於零 check_gt0 1 True    大於等於二 check_gt2 1 False    大於等於零 check_gt0 2 True    大於等於二 check_gt2 2 True    """

 

*************************************************************************************************************************************************************

2017-08-09 

由字串函數名得到對應的函數

把函數作為參數的用法比較直觀:

def func(a, b):    return a + bdef test(f, a, b):        print f(a, b)test(func, 3, 5)

 

但有些情況下,‘要傳遞哪個函數’這個問題事先還不確定,例如函數名與某變數有關。可以利用 func = globals().get(func_name) 來得到函數:

def func_year(s):    print ‘func_year:‘, s    def func_month(s):    print ‘func_month:‘, s  strs = [‘year‘, ‘month‘]for s in strs:    globals().get(‘func_%s‘ % s)(s)"""輸出:func_year: yearfunc_month: month"""

 

[Python] 動態函數調用(通過函數名)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.