我需要从列表中获取要作为参数调用的函数的名称。我用代码实现了这个(结果是b。如果我说liste [0]结果是a,那么它可以工作。):
def a():
print("aaaa")
return None
def b():
print("bbbb")
return None
liste = ['a','b']
inputMethodName = liste[1]
locals()[inputMethodName]()
但是在这个例子中我做同样的事情(至少我看到这就是为什么我问这个问题),它给出了一个错误。代码是:
filterPassFlag = 1
controlListForFilter = ['firstCharController']
def firstCharController(singleLine):
if singleLine[0] == "1":
filterPassFlag = 0
return None
def startControl(singleLine):
controlListForFilterIterator = 0
while (controlListForFilterIterator < len(controlListForFilter)) & (filterPassFlag == 1):
inputMethodName = controlListForFilter[controlListForFilterIterator]
locals()[inputMethodName](singleLine) #******ERROR IN THAT LINE.
controlListForFilterIterator = controlListForFilterIterator + 1
return None
singleLine = "bla bla bla bla"
startControl(singleLine)
输出是:
> Traceback (most recent call last): File
> "C:/Users/BerkayS/Desktop/phyondeneme/phytonTest.py", line 37, in
> <module>
> startControl(singleLine) File "C:/Users/BerkayS/Desktop/phyondeneme/phytonTest.py", line 24, in
> startControl
> locals()[inputMethodName](singleLine) KeyError: 'firstCharController' Process finished with exit code 1
当我删除该行包含错误(local()行)程序正在运行时。但两个例子之间的区别是什么?