python globals() 动态函数调用_[Python] 动态函数调用(通过函数名)
2018-04-09 update
利用python中的內(nèi)置函數(shù)?eval()?,函數(shù)說明:
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:
deffunction2(name, age):print("name: %s, age: %s" %(name, age))if __name__ == ‘__main__‘:
eval("function2")("Alice", 11)#或者:
args = ["Alice", 11]
kwargs={}
eval("function2")(*args, **kwargs)"""輸出結(jié)果都是:
name: Alice, age: 11"""
樣例2:
classTest(object):
states= [u"大于等于零", u"大于等于二"]
state2function= {u"大于等于零": "check_gt0", u"大于等于二": "check_gt2"}@staticmethoddefcheck_gt0(x):return x >=0
@staticmethoddefcheck_gt2(x):return x >= 2
defpredict(self, x):for state inTest.states:
check_ans= eval("Test." + Test.state2function[state])(x) #調(diào)用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
由字符串函數(shù)名得到對應(yīng)的函數(shù)
把函數(shù)作為參數(shù)的用法比較直觀:
deffunc(a, b):return a +bdeftest(f, a, b):printf(a, b)
test(func,3, 5)
但有些情況下,‘要傳遞哪個(gè)函數(shù)’這個(gè)問題事先還不確定,例如函數(shù)名與某變量有關(guān)。可以利用 func = globals().get(func_name) 來得到函數(shù):
deffunc_year(s):print ‘func_year:‘, sdeffunc_month(s):print ‘func_month:‘, s
strs= [‘year‘, ‘month‘]for s instrs:
globals().get(‘func_%s‘ %s)(s)"""輸出:
func_year: year
func_month: month"""
總結(jié)
以上是生活随笔為你收集整理的python globals() 动态函数调用_[Python] 动态函数调用(通过函数名)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [云炬创业基础笔记]第二章创业者测试19
- 下一篇: 最先进的响应式前端框架:Foundati