如何使用用户输入来调用用户定义的函数?

我有以下功能

def retrieve_phone_data():
      # function does something
   return phone_list

def retrieve_customer_data():
     #function does something
     return customer_info

def main(input1, input2):
    if input1 = 'phone' and input2 = 'customer':
    retrieve_phone_data()
    retrieve_customer_data()
  else:
  print('Please enter valid input')

Input1和Input2只能具有特定的值(现在先说电话和客户)。我有(超过10个函数),我不想使用If语句,因为它太多了。

我需要类似Excel中的vlookup之类的东西,我将创建可能的输入和辅助功能列表,以便每个有效的用户输入都将链接到该列表中的功能。有办法吗?

评论
糖小果
糖小果

You can use a dict here:

data_retrievers = {
    "phone": retrieve_phone_data,
    "customer": retrieve_customer_data,
}

然后在您的主要方法中:

if input in data_retrievers:
    data_retriever = data_retrievers[input]
    retrieved_data = data_retriever()
else:
    # Signify invalid input

If you want to add another input, you just add an entry to data_retrievers, with the key being input and the value being the corresponding function. Note the lack of () after the function names in data_retrievers, the function is only called when data_retriever is fetched.

点赞
评论