Switch in Python

后端 未结 7 1140
孤独总比滥情好
孤独总比滥情好 2021-01-01 22:34

I have tried making a switch like statement in python, instead of having a lot of if statements.

The code looks like this:

def findStuff(cds):
    L         


        
7条回答
  •  醉话见心
    2021-01-01 23:32

    (a) I fail to see what is wrong with if...elif...else

    (b) I assume that python does not have a switch statement for the same reason that Smalltalk doesn't: it's almost completely redundant, and in the case where you want to switch on types, you can add an appropriate method to your classes; and likewise switching on values should be largely redundant.

    Note: I am informed in the comments that whatever Guido's reason for not creating a switch in the first place, PEPs to have it added were rejected on the basis that support for adding such a statement is extremely limited. See: http://www.python.org/dev/peps/pep-3103/

    (c) If you really need switching behaviour, use a hashtable (dict) to store callables. The structure is:

    switch_dict = {
        Foo: self.doFoo,
        Bar: self.doBar,
        }
    
    func = switch_dict[switch_var]
    result = func() # or if they take args, pass args
    

提交回复
热议问题