0

我正在用 Python 制作一种编程语言。我希望能够通过键入以下内容来运行函数:

task $function:
    log "Hey!"

然后您可以通过键入以下内容来调用它:

$function

现在,我有这个代码:

def runFunction(self, f):
    ## Here's where I need help. How will you make a function that runs a function that doesn't exist in 
    ## the code?
...

elif i == 'task':
    self.string = line[5:]
    self.output = self.string.replace('{', '')
    self.function = self.output.replace('}', '')
...

elif i not in self.keywords and '$' in i:
    if i == self.function:
        self.runFunction(self.function)

我应该怎么做才能实现runFunction()功能?

4

1 回答 1

0

你能做什么?

您可以使用名为eval()的 python 内置函数 ,它可以让您动态评估表达式。

解决方案

def runFunction(self, f):
    eval(f)

其中 f 必须是一个字符串

如果你想创建函数:

您可以使用可以评估字符串的 exec() 。

示范:

exec("def myFunction(a,b): return a + b")

并像使用它一样

eval("myFunction(1,2)")
于 2020-09-20T09:35:04.083 回答