如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
如何使用带有函数名称的字符串调用函数?例如:
import foo
func_name = "bar"
call(foo, func_name) # calls foo.bar()
当前回答
我以前也遇到过类似的问题,那就是将字符串转换为函数。但我不能使用eval()或ast.literal_eval(),因为我不想立即执行这段代码。
例如,我有一个字符串“foo.bar”,我想将它指定给x作为函数名,而不是字符串,这意味着我可以在DEMAND上通过x()调用函数。
这是我的代码:
str_to_convert = "foo.bar"
exec(f"x = {str_to_convert}")
x()
至于您的问题,您只需要添加模块名foo和。在{}之前,如下所示:
str_to_convert = "bar"
exec(f"x = foo.{str_to_convert}")
x()
警告!!!eval()或exec()是一种危险的方法,您应该确认其安全性。警告!!!eval()或exec()是一种危险的方法,您应该确认其安全性。警告!!!eval()或exec()是一种危险的方法,您应该确认其安全性。
其他回答
只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用类似的方法:
# Get class from globals and create an instance
m = globals()['our_class']()
# Get the function (from the instance) that we need to call
func = getattr(m, 'function_name')
# Call it
func()
例如:
class A:
def __init__(self):
pass
def sampleFunc(self, arg):
print('you called sampleFunc({})'.format(arg))
m = globals()['A']()
func = getattr(m, 'sampleFunc')
func('sample arg')
# Sample, all on one line
getattr(globals()['A'](), 'sampleFunc')('sample arg')
如果不是类:
def sampleFunc(arg):
print('you called sampleFunc({})'.format(arg))
globals()['sampleFunc']('sample arg')
给定带有方法栏的模块foo:
import foo
bar = getattr(foo, 'bar')
result = bar()
getattr可以类似地用于类实例绑定方法、模块级方法、类方法。。。名单还在继续。
虽然getattr()是一种优雅的(大约快7倍)方法,但您可以使用eval从函数(local、class方法、模块)获得返回值,其优雅程度与x=eval('fo.bar')()相同。当您实现一些错误处理时,就会非常安全(getattr也可以使用相同的原理)。模块导入和类示例:
# import module, call module function, pass parameters and print retured value with eval():
import random
bar = 'random.randint'
randint = eval(bar)(0,100)
print(randint) # will print random int from <0;100)
# also class method returning (or not) value(s) can be used with eval:
class Say:
def say(something='nothing'):
return something
bar = 'Say.say'
print(eval(bar)('nice to meet you too')) # will print 'nice to meet you'
当模块或类不存在(键入错误或其他更好的错误)时,就会引发NameError。如果函数不存在,则引发AttributeError。这可用于处理错误:
# try/except block can be used to catch both errors
try:
eval('Say.talk')() # raises AttributeError because function does not exist
eval('Says.say')() # raises NameError because the class does not exist
# or the same with getattr:
getattr(Say, 'talk')() # raises AttributeError
getattr(Says, 'say')() # raises NameError
except AttributeError:
# do domething or just...
print('Function does not exist')
except NameError:
# do domething or just...
print('Module does not exist')
基于Patrick的解决方案,要动态获取模块,请使用以下方法导入:
module = __import__('foo')
func = getattr(module, 'bar')
func()
根据Python编程常见问题解答,最好的答案是:
functions = {'myfoo': foo.bar}
mystring = 'myfoo'
if mystring in functions:
functions[mystring]()
这种技术的主要优点是字符串不需要与函数的名称匹配。这也是用于模拟案例构造的主要技术