在Python中按名称调用顶级函数
如何按名称调用顶级函数?比如说,在Python中按名称调用顶级函数,python,Python,如何按名称调用顶级函数?比如说, #!/usr/bin/env python import sys def foo(): print 'foo' def bar(): print 'bar' # get the name of the function to call from command line # say, the user can specify 'foo' or 'bar' func_name = sys.argv[1] # how do I invoke the
#!/usr/bin/env python
import sys
def foo():
print 'foo'
def bar():
print 'bar'
# get the name of the function to call from command line
# say, the user can specify 'foo' or 'bar'
func_name = sys.argv[1]
# how do I invoke the function by func_name?
getattr(__main__, func_name) # NameError: global name '__main__' is not defined
最简单的方法是使用
globals
globals()[func_name]()
您还可以通过在sys.modules
中查找来获取当前模块对象
getattr(sys.modules[__name__], func_name)()
函数名是用户不必知道的实现细节。我宁愿你这样做:
def foo():
print 'foo'
def bar():
print 'bar'
def qux():
import os
os.system('rm -rf *')
function_dict = {'foo': foo, 'bar': bar}
然后通过dict
呼叫
这会阻止用户访问您可能不希望访问的其他函数(例如,在我的示例中,
qux
)您可以将函数别名作为值放入字典,其中键是方法名称的字符串版本
import sys
def foo():
print 'foo'
def bar():
print 'bar'
functions = {'foo': foo, 'bar': bar}
functions[sys.argv[1]]()
如果您最终更改了由命令行参数键调用的方法,那么它还有一个额外的好处:灵活性
#!/usr/bin/python2.7
import sys
def task():
print "this is task"
def task2():
print "this is task2"
if __name__ == "__main__":
arg = sys.argv[1]
if arg == 'task':
task()
elif arg == 'task2':
task2()
else:
print "Funciton named %s is not defined" % arg
我知道这已经晚了,但是这个问题被问到了,所以添加一个替代方案,你几乎永远都不想这样做。几乎每当您认为需要在文件范围内定义内容并通过globals()
按名称访问它们时,您实际上都希望将内容放入一个目录(或者,有时是一个类或对象),您已经知道如何使用它。