繁体   English   中英

如何取一个字符串并将其用作标识符来调用函数?

[英]How to take a string and use it as an identifier to call a function?

我为我的类创建了一个自动分级器,它使用命令行参数来调用该问题集的关联函数。 我需要将命令行参数提取为字符串,然后将其用作函数调用。 在示例中,我将字符串分配给 pset,然后调用 pset 并将 studentFile 作为参数传递。 问题在于解释器将其视为字符串而不是标识符。

这是我的代码的图片

if len(sys.argv) == 2:
    try:
        # find and store the file
        studentFile = helpers.findInSubdirectory(sys.argv[1])
        for i in studentFile.split('/'):
            if i.endswith('.py'):
                pset = i[:-3]
        pset(studentFile)

一种不安全的方法是使用eval或查看globals()字典。 稍微安全一点的方法是在字典中创建一个字符串到函数的映射,然后从映射中查找函数。

def foo():
    print('hi')

def bar():
    print('see you')

funs = { 'foo': foo, 'bar': bar }
funs['foo']()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM