简体   繁体   English

替换字典/案例的Python字典替换

[英]Fall-through in Python dictionary replacement of switch/case

I try to implement switch/case mechanism in Python. 我尝试在Python中实现switch / case机制。 After reading several websites and questions here (eg this one ), I built the code below. 在阅读了几个网站和问题(例如, 这个 )之后,我构建了以下代码。 But it behaves wrong, having what I understand to be - a fall-through, which can be even problematic to get , surely not a default expected result. 但是它的行为是错误的,据我所知-失败, 获取甚至可能有问题 ,肯定不是默认的预期结果。

def something():
    print 'something'

def somethingElse():
    print 'something else'

def switch():
    cases = {
        0: something(),
        1: something(),
        2: something(),
        3: something(),
        4: something(),
        5: something()
        }

    cases.get(2, somethingElse())

switch()

(Obviously the same switch for every case is just for the sake of the example) (显然,每种情况都使用相同的开关只是为了示例)

When I run it I expect something() to be run only once (as I manually input 2 ). 当我运行它时,我希望something()仅运行一次(因为我手动输入2 )。 However, the output in the console is: 但是,控制台中的输出为:

something
something
something
something
something
something
something else

What means it was run 6 times plus the default value run. 这意味着它已经运行了6次加上默认值运行。 I cannot understand what in this code allows for such a fall-through? 我不明白这段代码中允许发生这种情况的原因是什么? Or maybe the problem is different? 也许问题不同?

This is Python 2.7.12 here. 这是Python 2.7.12。

Your dictionary is calling every single function when it creates the cases. 您的字典在创建案例时会调用每个函数。 Your functions print (a side effect) rather than return a string so you see all of the strings printed to console. 您的函数打印(副作用)而不是返回字符串,因此您看到所有打印到控制台的字符串。

Instead, your switch should return a function and then you can call that function. 相反,您的开关应返回一个函数,然后您可以调用该函数。

def something():
    print 'something'

def somethingElse():
    print 'something else'

def switch():
    cases = {
        0: something,
        1: something,
        2: something,
        3: something,
        4: something,
        5: something
        }

    # All of the values in `cases` are functions so it is safe
    # to call whatever `cases.get(...)` returns.
    cases.get(2, somethingElse)()

switch()

You need to return function name and then call it. 您需要返回函数名称,然后调用它。 Like this 像这样

def something():
    print ('something')

def somethingElse():
    print ('something else')

cases = {1: something, 2: something, 3:something, 4:something,5:something}
result = cases.get(2, somethingElse)()

~

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM