加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python中的Switch / Case实现有什么价值吗?

发布时间:2020-12-20 12:42:04 所属栏目:Python 来源:网络整理
导读:最近,我在网上看到一些关于如何在 Python中没有好的“switch / case”等级的讨论.我意识到有几种方法可以做类似的事情 – 一些是lambda,一些是字典.关于替代方案,还有其他StackOverflow讨论.甚至有两个PEP(PEP 0275和PEP 3103)讨论(并拒绝)将开关/案例集成到
最近,我在网上看到一些关于如何在 Python中没有好的“switch / case”等级的讨论.我意识到有几种方法可以做类似的事情 – 一些是lambda,一些是字典.关于替代方案,还有其他StackOverflow讨论.甚至有两个PEP(PEP 0275和PEP 3103)讨论(并拒绝)将开关/案例集成到语言中.

我想出了我认为做切换/案例的优雅方式.

最终看起来像这样:

from switch_case import switch,case         # note the import style

x = 42
switch(x)                                    # note the switch statement
if case(1):                                  # note the case statement
    print(1)
if case(2):
    print(2)
if case():                                   # note the case with no args
    print("Some number besides 1 or 2")

所以,我的问题是:这是一个有价值的创作吗?你对改善它有什么建议吗?

我把include file on github和大量的例子放在一起. (我认为整个包含文件大约有50个可执行行,但我有1500行示例和文档.)我是否过度设计了这个东西,浪费了大量时间,还是有人觉得这个值得?

编辑:

试图解释为什么这与其他方法不同:
????1)可以有多条路径(执行两种或更多种情况),
???????这在字典方法中更难.
????2)可以检查“等于”以外的比较
???????(例如case(less_than(1000)).
????3)比字典方法更可读,并且可能是/ elif方法
????4)可以跟踪有多少真实案例.
????5)可以限制允许的真实案例数量. (即执行
???????前2个……的真实案例
????6)允许默认情况.

这是一个更详细的例子:

from switch_case import switch,case,between

x=12
switch(x,limit=1)                # only execute the FIRST True case
if case(between(10,100)):         # note the "between" case Function
    print ("%d has two digits."%x)
if case(*range(0,100,2)):         # note that this is an if,not an elif!
    print ("%d is even."%x)       # doesn't get executed for 2 digit numbers,# because limit is 1; previous case was True.
if case():
    print ("Nothing interesting to say about %d"%x)



# Running this program produces this output:

12 has two digits.

下面是一个示例,试图说明switch_case如何比传统的if / else更清晰简洁:

# conventional if/elif/else:
if (status_code == 2 or status_code == 4 or (11 <= status_code < 20) 
          or status_code==32):
    [block of code]
elif status_code == 25 or status_code == 45:
    [block of code]
if status_code <= 100:
    [block can get executed in addition to above blocks]

# switch_case alternative (assumes import already)
switch(status_code)
if case (2,4,between(11,20),32):   # significantly shorter!
    [block of code]
elif case(25,45):
    [block of code]
if case(le(100)):
    [block can get executed in addition to above blocks]

如果相同的开关一遍又一遍地重复,则可以节省很多时间.不确定用例有多频繁,但似乎某些情况下这是有道理的.

github上的示例文件有更多示例.

解决方法

from pyswitch import Switch   # pyswitch can be found on PyPI

myswitch = Switch()

@myswitch.case(42)
def case42(value):
    print "I got 42!"

@myswitch.case(range(10))
def caseRange10(value):
    print "I got a number from 0-9,and it was %d!" % value

@myswitch.caseIn('lo')
def caseLo(value):
    print "I got a string with 'lo' in it; it was '%s'" % value

@myswitch.caseRegEx(r'b([Pp]yw)b')
def caseReExPy(matchOb):
    print r"I got a string that matched the regex 'b[Pp]ywb',and the match was '%s'" % matchOb.group(1)

@myswitch.default
def caseDefault(value):
    print "Hey,default handler here,with a value of %r." % value

myswitch(5)  # prints: I got a number from 0-9,and it was 5!
myswitch('foobar')  # prints: Hey,with a value of foobar.
myswitch('The word is Python')  # prints: I got a string that matched the regex 'b[Pp]ywb',and the match was 'Python'

你明白了.为什么?是的,调度表是Python的发展方向.我只是厌倦了一遍又一遍地写它们,所以我写了一个类和一些装饰器来为我处理它.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读