简体   繁体   English

如何从同一个字典中存储然后调用字符串和函数?

[英]How do I store and then call strings and functions from the same dictionary?

I've been trying to store and then call a string and/or a function inside a dictionary.我一直在尝试在字典中存储然后调用字符串和/或函数。

First example第一个例子

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

mainfunction()

This works only if I input the key 'x'.这仅在我输入键“x”时才有效。 If I try to input key 'y', I get this error.如果我尝试输入键“y”,则会出现此错误。

TypeError: 'str' object is not callable

Also, the problem with this method is that it can't make a default answer.此外,这种方法的问题在于它无法做出默认答案。

Second example第二个例子

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()

This method works for key 'y', but for key 'x' it prints something to the effect of:此方法适用于键 'y',但对于键 'x' 它打印的效果如下:

<function secondfunc at 0x7ab4496dc0>

I'm trying to make it so that whichever value I input, it will either print a default value, print a string, or execute a function.我试图让它无论我输入哪个值,它都会打印默认值、打印字符串或执行函数。 All depending on the key input.一切都取决于按键输入。

Last example最后一个例子

The only solution I've found is that which uses if statements.我发现的唯一解决方案是使用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()

This solution takes more code than I would like it to, and it also requires an if statement specific to the dictionary given, which takes more time.这个解决方案需要比我想要的更多的代码,而且它还需要一个特定于给定字典的if语句,这需要更多的时间。 Is there no better way to do this?没有更好的方法来做到这一点吗?

Instead of a string itself, you need to store a function returning a string in the dictionary.您需要在字典中存储一个返回字符串函数,而不是字符串本身。

Most simply this can be done as an anonymous function using the lambda syntax:最简单的是,这可以使用lambda语法作为匿名函数完成:

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

(It's bad practice to name this dictionary dict , because it shadows the built-in dict , so I'll use a better name here.) (将这个字典命名为dict是不好的做法,因为它隐藏了内置的dict ,所以我将在这里使用一个更好的名字。)

Of course, secondfunc should not print a string, but return a string, as well, since printing is already the job of mainfunc (see also: Difference between returns and printing in python? ):当然, secondfunc不应该打印字符串,而应该返回一个字符串,因为打印已经是mainfunc的工作(另请参阅: python 中返回和打印之间的区别? ):

def secondfunc():
    return 'hi world'

Now, print(answers['x']()) and print(answers['y']()) are working equally.现在, print(answers['x']())print(answers['y']())工作相同。

To create a default answer with the dictionary .get() method, it also needs to be a function returning a string:要使用字典.get()方法创建默认答案,它还需要是一个返回字符串的函数:

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

You can use the callable() function to test if the dictionary value is a function.您可以使用callable()函数来测试字典值是否为函数。 If it is, call it, otherwise just print the value itself.如果是,调用它,否则只打印值本身。

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)

You can use the callable() built-in function to test if the given object is callable.您可以使用callable()内置函数来测试给定的对象是否可调用。

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

You can use isinstance() to check whether it's a FunctionType or not:您可以使用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM