如何从 switch case 调用方法?

我试图在我的工具中实现一个菜单。但是我无法在 python 中实现 switch case。我知道python只有字典映射。如何在那些 switch case 中调用参数化方法?例如,我有这个程序


def Choice(i):

    switcher = {

            1: subdomain(host),

            2: reverseLookup(host),

            3: lambda: 'two'

        }

    func = switcher.get(i, lambda:'Invalid')

    print(func())


在这里,我无法执行参数化调用subdomain(host)。请帮忙。


MYYA
浏览 385回答 3
3回答

慕无忌1623718

我认为问题是因为在switcher创建字典时会调用前两个函数。您可以通过lambda如下所示的所有值函数定义来避免这种情况:def choice(i):    switcher = {            1: lambda: subdomain(host),            2: lambda: reverseLookup(host),            3: lambda: 'two'        }    func = switcher.get(i, lambda: 'Invalid')    print(func())

潇潇雨雨

有一个选项很明显是正确的..:def choice(i, host):  # you should normally pass all variables used in the function    if i == 1:        print(subdomain(host))    elif i == 2:        print(reverseLookup(host))    elif i == 3:        print('two')    else:        print('Invalid')如果您使用的是字典,重要的是所有的 rhs(右侧)都具有相同的类型,即采用零参数的函数。当我使用 dict 来模拟 switch 语句时,我更喜欢将 dict 放在使用它的地方:def choice(i, host):    print({        1: lambda: subdomain(host),        2: lambda: reverseLookup(host),        3: lambda: 'two',    }.get(i, lambda: 'Invalid')())   # note the () at the end, which calls the zero-argument function returned from .get(..)

白板的微信

可以使用 Python 中的字典映射来实现切换案例,如下所示:def Choice(i):    switcher = {1: subdomain, 2: reverseLookup}    func = switcher.get(i, 'Invalid')    if func != 'Invalid':        print(func(host))有一个字典switcher有助于根据函数的输入映射到正确的函数Choice。有要实现的默认情况,使用 完成switcher.get(i, 'Invalid'),因此如果返回'Invalid',您可以向用户提供错误消息或忽略它。调用是这样的:Choice(2)  # For example请记住host在调用 之前设置值Choice。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python