python globals() 动态函数调用_[Python] 动态函数调用(通过函数名)

本文介绍了如何在Python中使用`globals()`函数动态地调用函数。通过示例1展示了基本的函数调用,而在示例2中演示了在类中根据字符串动态调用类方法。同时,还提到了利用`globals().get()`来根据字符串获取并执行函数的方法。
摘要由CSDN通过智能技术生成

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:

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)"""输出结果都是:

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) #调用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

由字符串函数名得到对应的函数

把函数作为参数的用法比较直观:

deffunc(a, b):return a +bdeftest(f, a, b):printf(a, b)

test(func,3, 5)

但有些情况下,‘要传递哪个函数’这个问题事先还不确定,例如函数名与某变量有关。可以利用 func = globals().get(func_name) 来得到函数:

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"""

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值