在Python中使用同一模块内的字符串调用函数? [英] Calling a function from string inside the same module in Python?

查看:161
本文介绍了在Python中使用同一模块内的字符串调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在一个名为 foo.py 的模块内部有一个函数 bar 。在foo.py的某处,我希望能够从字符串bar中调用bar()。

 #filename:foo.py 
导入sys

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

if __name__ =='__main__':
funcname ='bar'
#这里我应该可以从funcname

调用bar()我知道存在一些内置函数在python中称为'getattr'。但是,它需要'模块对象'作为第一个参数。如何获取当前模块的'模块对象'?

解决方案

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

  func_I_want =获取函数
func_I_want()#call it



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

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

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


Lets say I have a function bar inside a module called foo.py . Somewhere inside foo.py, I want to be able to call bar() from the string "bar". How do I do that?

# 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

I know that there exists some built-in function in python called 'getattr'. However, it requires 'module object' to be the first parameter. How to obtain the 'module object' of the current module?

解决方案

globals is probably easier to understand. It returns the current module's __dict__, so you could do:

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

If you really want the module object, you can get it from sys.modules (but you usually don't need it):

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

Note that in general, you should ask yourself why you want to do this. This will allow any function to be called via a string -- which is probably user input... This can have potentially bad side effects if you accidentally give users access to the wrong functions.

这篇关于在Python中使用同一模块内的字符串调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆