【问题标题】:How to take a string and use it as an identifier to call a function?如何获取一个字符串并将其用作调用函数的标识符?
【发布时间】:2020-10-20 14:13:33
【问题描述】:

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

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)

【问题讨论】:

标签: python string function identifier


【解决方案1】:

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

def foo():
    print('hi')

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

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

【讨论】:

  • 使用字典是可行的,但它仍然需要我创建另一个结构来包含函数调用。我希望有一种更简单的方法可以将字符串转换为标识符。谢谢。
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 2020-07-11
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 2018-03-06
相关资源
最近更新 更多