Python:使用变量引用不同的函数
我正在用Python 3.5编写一个程序,当您输入不同的输入时,该程序将运行不同的函数:Python:使用变量引用不同的函数,python,function,Python,Function,我正在用Python 3.5编写一个程序,当您输入不同的输入时,该程序将运行不同的函数: commandList = ["test1", "test2", "test3"] def test1(): print("TEST 1 FUNCTION") def test2(): print("TEST 2 FUNCTION") def test3(): print("TEST 3 FUNCTION") while True: userRaw = input(">
commandList = ["test1", "test2", "test3"]
def test1():
print("TEST 1 FUNCTION")
def test2():
print("TEST 2 FUNCTION")
def test3():
print("TEST 3 FUNCTION")
while True:
userRaw = input(">:")
user = userRaw.lower()
for x in range(len(commandList)):
if user == commandList[x]:
# Needs to run function which has the same name as the string 'user'
# E.g. if user = 'test1' then function test1() is run.
在if
语句(注释在哪里)之后,我需要输入什么
我尝试过这样做,但没有成功:
commandList = ["test1", "test2", "test3"]
def function(test1):
print("TEST 1 FUNCTION")
def function(test2):
print("TEST 2 FUNCTION")
def function(test3):
print("TEST 3 FUNCTION")
while True:
userRaw = input(">:")
user = userRaw.lower()
for x in range(len(commandList)):
if user == commandList[x]:
function(user)
我试图避免使用大量的
if
语句,因为我的目标是使代码易于扩展(快速添加新函数)。您用相同的名称命名了函数,因此它可能不起作用
但让我们做得更好。使用字典:
def function1():
print('foo')
def bad_choice():
print('Too bad')
...
function_mapper = {'test1': function1, 'test2': function2, 'test3': function3}
user_input = input('Please enter your choice: ')
chosen_function = function_mapper.get(user_input, bad_choice)
chosen_function()
您将所有函数命名为同一个名称!谢谢你的回答,但我想我会从@Coldspeed中找到答案,因为它更重要concise@LoganMiller今天它可能看起来更简洁,但在6个月后,当您再次查看代码并努力理解正在发生的事情时,您可能希望使用这个答案。一般来说,在编程时,今天采用快速解决方案将使明天的调试更加困难。