如何使用带有函数名称的字符串调用函数?例如:

import foo
func_name = "bar"
call(foo, func_name)  # calls foo.bar()

当前回答

这是一个简单的答案,例如,这将允许您清除屏幕。下面有两个示例,分别是eval和exec,它们将在清理后在顶部打印0(如果您使用的是Windows,请将clear更改为cls,例如,Linux和Mac用户保持原样)或仅执行它。

eval("os.system(\"clear\")")
exec("os.system(\"clear\")")

其他回答

给定带有方法栏的模块foo:

import foo
bar = getattr(foo, 'bar')
result = bar()

getattr可以类似地用于类实例绑定方法、模块级方法、类方法。。。名单还在继续。

答案(我希望)从来没有人想要

Eval样行为

getattr(locals().get("foo") or globals().get("foo"), "bar")()

为什么不添加自动导入

getattr(
    locals().get("foo") or 
    globals().get("foo") or
    __import__("foo"), 
"bar")()

万一我们有多余的字典要查

getattr(next((x for x in (f("foo") for f in 
                          [locals().get, globals().get, 
                           self.__dict__.get, __import__]) 
              if x)),
"bar")()

我们需要更深入

getattr(next((x for x in (f("foo") for f in 
              ([locals().get, globals().get, self.__dict__.get] +
               [d.get for d in (list(dd.values()) for dd in 
                                [locals(),globals(),self.__dict__]
                                if isinstance(dd,dict))
                if isinstance(d,dict)] + 
               [__import__])) 
        if x)),
"bar")()

这是一个简单的答案,例如,这将允许您清除屏幕。下面有两个示例,分别是eval和exec,它们将在清理后在顶部打印0(如果您使用的是Windows,请将clear更改为cls,例如,Linux和Mac用户保持原样)或仅执行它。

eval("os.system(\"clear\")")
exec("os.system(\"clear\")")

还没有人提到operator.attrgetter:

>>> from operator import attrgetter
>>> l = [1, 2, 3]
>>> attrgetter('reverse')(l)()
>>> l
[3, 2, 1]
>>> 

只是一个简单的贡献。如果我们需要实例化的类在同一个文件中,我们可以使用类似的方法:

# 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')