【问题标题】:Python: How to use a dictionary to call methods (values in dictionary) to run based on user input (key in dictionary) in a different function?Python:如何使用字典调用方法(字典中的值)以根据用户输入(字典中的键)在不同的函数中运行?
【发布时间】:2019-12-04 05:55:36
【问题描述】:

到目前为止我所拥有的:

def run_A():
   # code...

def run_B():
   # code...

def run_C():
   # code...

inputDict = {'a': run_A, 'b': run_B, 'c': run_C, 'q': False}  # q for quit program
def userChoice(self):
    y = True
    while y:
       choice = input("a. run A\nb. run B\nc. run C\nq. Quit").lower()
       self.inputDict[choice]

我的问题是程序允许用户输入他们的选择,但该函数将根据字典调用(不会运行)并且程序只会不断询问用户他们的选择。

【问题讨论】:

  • 如果函数是类的一部分,请将整个代码写在这里。
  • 从您的问题看来,您有两个问题 1:字典调用不运行该函数,因为它检索函数名称。这可以通过以下关于“eval()”的答案来解决。但是你关于“程序只会不断询问用户他们的选择”的第二个问题,如果你想解决这个问题,我们需要知道你想要什么。您是否希望程序只询问一次(删除while)?您是否希望它在每次用户输入时询问一次?

标签: python python-3.x dictionary lookup-tables


【解决方案1】:

self.inputDict[choice] 只会从 dict 中获取函数,不会调用它,所以也许你需要将 self.inputDict[choice] 替换为 self.inputDict[choice]()

【讨论】:

  • 我想通了:应该是self.inputDict[choice](self)
【解决方案2】:
def run_A():
    print("A")
   # code...

def run_B():
    print("B")
   # code...

def run_C():
    print("C")
   # code...

inputDict = {'a': run_A, 'b': run_B, 'c': run_C, 'q': False}  # q for quit program
def userChoice(self):
    y = True
    while y:
       choice = input("a. run A\nb. run B\nc. run C\nq. Quit").lower()
       if choice =="q":
           y = False
       else:
           self.inputDict[choice]()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-13
    • 2019-06-26
    • 1970-01-01
    • 2021-12-21
    • 2017-04-15
    • 1970-01-01
    • 2019-05-02
    • 2022-11-14
    相关资源
    最近更新 更多