【问题标题】:How do I store and then call strings and functions from the same dictionary?如何存储然后调用同一字典中的字符串和函数?
【发布时间】:2021-09-29 03:47:35
【问题描述】:

我一直在尝试在字典中存储然后调用字符串和/或函数。

第一个例子

def mainfunction():
    dict = {
        'x' : secondfunc,
        'y' : 'hello world'
    }
    while True :
        inpt = input('@')
        dict[inpt]()
    
def secondfunc():
    print('hi world')

mainfunction()

这仅在我输入键“x”时才有效。 如果我尝试输入键“y”,我会收到此错误。

TypeError: 'str' object is not callable

另外,这个方法的问题是它不能做出默认答案。

第二个例子

def mainfunction():
    dict = {
        'x' : secondfunc,
        'y' : 'hello world'
    }
    while True:
        inpt = input('@')
        z = dict.get(inpt, 'Default text')
        print(z)
        
def secondfunc():
    print('hi world')
    
mainfunction()

此方法适用于键“y”,但对于键“x”,它会打印以下内容:

<function secondfunc at 0x7ab4496dc0>

我试图让它无论我输入哪个值,它都会打印一个默认值、打印一个字符串或执行一个函数。一切都取决于按键输入。

最后一个例子

我发现的唯一解决方案是使用if 语句。

def mainfunction():
    dict = {
        'x' : secondfunc,
    }
    dict2 = {
        'y' : 'hello world'
    }
    
    while True:
        inpt = input('@')
        z = dict2.get(inpt, 'Default text')
        if inpt == 'x':
            dict[inpt]()
        else:
            print(z)
        
def secondfunc():
    print('hi world')
    
mainfunction()

此解决方案需要的代码比我希望的要多,而且它还需要特定于给定字典的if 语句,这需要更多时间。 没有更好的方法吗?

【问题讨论】:

    标签: python string function dictionary


    【解决方案1】:

    您需要在字典中存储一个返回字符串的函数,而不是字符串本身。

    这可以使用lambda 语法作为匿名函数完成:

    answers = {
        'x': secondfunc,
        'y': lambda: 'hello world'
    }
    

    (将此字典命名为dict 是不好的做法,因为它会影响内置的dict,所以我将在这里使用更好的名称。)

    当然,secondfunc 不应该打印一个字符串,而应该返回一个字符串,因为打印已经是mainfunc 的工作(另见:Difference between returns and printing in python?):

    def secondfunc():
        return 'hi world'
    

    现在,print(answers['x']())print(answers['y']()) 工作正常。

    要使用字典.get() 方法创建默认答案,它还需要是一个返回字符串的函数:

    def mainfunction():
        answers = {
            'x' : secondfunc,
            'y' : lambda: 'hello world'
        }
        while True:
            inpt = input('@')
            z = answers.get(inpt, lambda: 'Default text')()
            print(z)
    

    【讨论】:

    • 谢谢,不再需要 IF 语句。
    【解决方案2】:

    您可以使用isinstance() 来检查它是否是FunctionType

    from types import FunctionType
    
    def mainfunction():
        d = {
            'x': secondfunc,
            'y': 'hello world'
        }
        while True:
            inpt = input('@')
            res = d.get(inpt, 'default')
            if isinstance(res, FunctionType):
                res()
            else:
                print(res)
    
    def secondfunc():
        print('hi world')
    
    mainfunction()
    

    【讨论】:

      【解决方案3】:

      您可以使用callable() 内置函数来测试给定对象是否可调用。

      z = dict2.get(inpt, 'Default text')
      if callable(z):
          z()
      else:
          print(z)
      

      【讨论】:

        【解决方案4】:

        您可以使用callable() 函数来测试字典值是否为函数。如果是,则调用它,否则只打印值本身。

        def mainfunction():
            dict = {
                'x' : secondfunc,
                'y' : 'hello world'
            }
            while True:
                inpt = input('@')
                z = dict.get(inpt, 'Default text')
                if callable(z):
                    z()
                else:
                    print(z)
        

        【讨论】:

          猜你喜欢
          • 2018-10-13
          • 2013-08-07
          • 1970-01-01
          • 2021-11-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-07
          • 2013-05-23
          相关资源
          最近更新 更多