python中通過字符串來調用函數,通過字符串來調用變量,將字符串變成變量名


 

強調:eval()函數功能雖然強大,但是也很危險,這個方法需要慎重使用。

利用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
    """
復制代碼

 

 

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

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

復制代碼
def func(a, b):
    return a + b

def 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: year
func_month: month
"""
復制代碼

 將字符串變成變量名:

https://www.cnblogs.com/kaerxifa/p/11424796.html

 

參考文章:https://www.cnblogs.com/bymo/p/7327732.html


免責聲明!

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



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