简体   繁体   English

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

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

I have created an autograder for my classes that uses a command line argument to call the associated function for that problem set.我为我的类创建了一个自动分级器,它使用命令行参数来调用该问题集的关联函数。 I need to extract the command line argument as a string, and then use it as a function call.我需要将命令行参数提取为字符串,然后将其用作函数调用。 In the example I'm assigning the string to pset and then calling pset and passing studentFile as the argument.在示例中,我将字符串分配给 pset,然后调用 pset 并将 studentFile 作为参数传递。 The problem is that the interpreter sees it as a string and not an identifier.问题在于解释器将其视为字符串而不是标识符。

this is a picture of my code这是我的代码的图片

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)

An unsafe way to do this would be to use eval or look at the globals() dictionary.一种不安全的方法是使用eval或查看globals()字典。 A slightly safer way would be to create a string-to-function mapping in a dictionary, and look up the function from the mapping.稍微安全一点的方法是在字典中创建一个字符串到函数的映射,然后从映射中查找函数。

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