为什么 Python 没有 switch-case? [英] Why doesn't Python have switch-case?

查看:52
本文介绍了为什么 Python 没有 switch-case?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

更新: 新语法(超越简单的 case 语句)已被接受以包含在 Python 3.10 中,请参阅 PEP 634 结构模式匹配:规范.

Update: New syntax (which goes beyond a simple case statement) has been accepted for inclusion in Python 3.10, see PEP 634 Structural Pattern Matching: Specification.

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

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.

参见 PEP 275PEP 3103 进行全面讨论.

See PEP 275 and PEP 3103 for a full discussion.

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

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

这篇关于为什么 Python 没有 switch-case?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆