为了账号安全,请及时绑定邮箱和手机立即绑定

如何从 switch case 调用方法?

如何从 switch case 调用方法?

MYYA 2021-09-24 13:49:37
我试图在我的工具中实现一个菜单。但是我无法在 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)。请帮忙。
查看完整描述

3 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

我认为问题是因为在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())


查看完整回答
反对 回复 2021-09-24
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

有一个选项很明显是正确的..:


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



查看完整回答
反对 回复 2021-09-24
?
白板的微信

TA贡献1883条经验 获得超3个赞

可以使用 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。


查看完整回答
反对 回复 2021-09-24
  • 3 回答
  • 0 关注
  • 384 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号