本渣PHP屌丝一枚,最近在用Python做一个东西碰到了这个问题,在这里给没踩过坑的朋友分享下
以Python 2.7为例

从前有座山
碰到参数特别多的情况的时候总是看着一堆if...else if抓狂,斩不断,理还乱,幸好有Switch...Case可以很方便的处理多种情况的参数
但是在Python中没有Switch...Case。。。

参考网上很多文章,Get到了通过字典的方式实现Switch...Case
山上有座庙
字典的用法如下

通过li.get('')的方法可以返回对应的值
default值可以通过get()的参数实现

这里要实现Switch...Case,可以将执行的操作定义为函数,然后将函数名存于字典中

运行结果

到此,就可以实现在Python中Switch...Case的方法了
庙里有个老和尚
在这里又碰到一个问题,在面向对象中怎么去实现
摸索过后发现也很简单
li = {
'a':self.__a
示例代码

运行结果

网友评论