【问题标题】:Calling a function from string inside the same module in Python?在 Python 中从同一模块内的字符串调用函数?
【发布时间】:2012-10-02 12:01:23
【问题描述】:

假设我在一个名为 foo.py 的模块中有一个函数 bar 。在 foo.py 的某个地方,我希望能够从字符串“bar”调用 bar()。我该怎么做?

# filename: foo.py
import sys

def bar():
  print 'Hello, called bar()!'

if __name__ == '__main__':
  funcname = 'bar'
  # Here I should be able to call bar() from funcname

我知道在 python 中存在一些名为“getattr”的内置函数。但是,它需要“模块对象”作为第一个参数。如何获取当前模块的“模块对象”?

【问题讨论】:

    标签: python string function


    【解决方案1】:

    globals 可能更容易理解。它返回当前模块的__dict__,所以你可以这样做:

    func_I_want = globals()['bar']  #Get the function
    func_I_want()    #call it
    

    如果你真的想要模块对象,你可以从sys.modules得到它(但你通常不需要它):

    import sys.modules
    this_mod = sys.modules[__name__]
    func = getattr(this_mod,'bar')
    func()
    

    请注意,一般来说,您应该问自己为什么要这样做。这将允许通过字符串调用任何函数——这可能是用户输入...如果您不小心让用户访问错误的函数,这可能会产生不良的副作用。

    【讨论】:

      【解决方案2】:

      使用字典来保存您要调用的函数的映射:

      if __name__ == '__main__':
        funcnames = {'bar': bar}
        funcnames['bar']()
      

      【讨论】:

      • 我总是很欣赏能解决 OP 的 问题 而不是她/他的 question 的答案。 +1
      猜你喜欢
      • 1970-01-01
      • 2010-09-05
      • 2011-10-02
      • 1970-01-01
      • 2010-09-05
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多