为什么 Python 没有 switch-case?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46701063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:46:16  来源:igfitidea点击:

Why doesn't Python have switch-case?

pythonswitch-statement

提问by T1412

Please explain why Python does not have the switch-case feature implemented in it.

请解释为什么 Python 中没有实现 switch-case 功能。

回答by Raymond Hettinger

We considered it at one point, but without having a way to declare named constants, there is no way to generate an efficient jump table. So all we would be left with is syntactic sugar for something we could already do with if-elif-elif-else chains.

我们曾经考虑过,但是没有办法声明命名常量,也就没有办法生成一个高效的跳转表。所以我们只剩下语法糖,我们可以用 if-elif-elif-else 链做一些事情。

See PEP 275and PEP 3103for a full discussion.

有关完整讨论,请参阅PEP 275PEP 3103

Roughly the rationale is that the various proposals failed to live up to people's expections about what switch-case would do, and they failed to improve on existing solutions (like dictionary-based dispatch, if-elif-chains, getattr-based dispatch, or old-fashioned polymorphism dispatch to objects with differing implementations for the same method).

大致的理由是,各种提案未能达到人们对 switch-case 会做什么的期望,并且他们未能改进现有的解决方案(如基于字典的调度、if-elif-chains、基于 getattr 的调度,或老式的多态分派到具有相同方法的不同实现的对象)。

回答by wim

There is literally a section in the docs to answer this. See below:

文档中有一个部分可以回答这个问题。见下文:

Why isn't there a switch or case statement in Python?

为什么 Python 中没有 switch 或 case 语句?

TL;DR: existing alternatives (dynamic dispatch via getattror dict.get, if/elifchains) cover all the use cases just fine.

TL;DR:现有的替代方案(通过getattrdict.getif/elif链动态调度)涵盖了所有用例就好了。

回答by vedant patel

def f(x):
    return {
        1 : 'output for case 1',
        2 : 'output for case 2',
        3 : 'output for case 3'
    }.get(x, 'default case')   

You can use this as switch case in python and if condition not match it will return default if condition not match

您可以将其用作 python 中的 switch case,如果条件不匹配,则如果条件不匹配,它将返回默认值