【问题标题】:python function with the same name being called based on user input基于用户输入调用具有相同名称的python函数
【发布时间】:2018-01-04 19:19:39
【问题描述】:

您好,我正在尝试根据用户输入调用一个或多个函数。这是我到目前为止所写的。

a = 0
b = 1
c = 2
def keyword(a):
  print("what is the boss")
def keyword(b):
  print("who is the boss")
def keyword(c):
  print("where is the boss")


key_words=["what","who","where","when","why"]
x= input("ask.. ").split()
for a in x:
   if str(a) in key_words:
      keyword(key_words.index(a))

这是我的代码,我被卡住了,请帮忙。问题是它没有选择正确的功能

【问题讨论】:

  • 那么,这三个函数在顶部都称为keyword?当程序执行时,只有最后一个可以使用。每次您使用相同名称设置新函数时,它都会覆盖该名称的任何先前函数。

标签: python function keyword


【解决方案1】:

您只能拥有一个同名的函数(变量)。对于您的示例,请使用字典:

keywords = {
    "what": lambda: print("what is the boss"),
    "who": lambda: print("who is the boss"),
    "where": lambda: print("where is the boss"),
}

words = input("ask.. ").split()
for word in words:
   if word in keywords:
      keywords[word]()

【讨论】:

    【解决方案2】:

    一般来说,不是函数的工作方式(有一些例外,但与您的情况没有任何相似之处)。

    一个函数可以实现你的愿望,它根据传递给它的参数打印结果。

    像这样:

    def keyword(a):
        if a == 0:
            print("what is the boss")
        elif a == 1:
            print("who is the boss")
        elif a == 2:
            print("where is the boss") 
    

    其余代码可以相同,只是你根本不需要设置a、b、c变量。

    【讨论】:

      【解决方案3】:

      正如 Andrew 已经指出的那样,您的函数正在覆盖之前的函数。这可以做你想要输出的东西,但可能不是你想要学习的东西。

      def keyword(word):
        print(word + " is the boss")
      
      #key_words=["what","who","where"]
      x= input("ask.. ").split()
      for a in x:
          if str(a) in key_words:
              keyword(a)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-09
        • 2017-08-17
        • 1970-01-01
        • 1970-01-01
        • 2011-09-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多