How to implement switch/case statement in Python

不言
Release: 2018-09-18 15:21:16
Original
8752 people have browsed it

The content of this article is about the method of implementing switch/case statements in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

There is no Switch/Case statement in Python. Many people think that this statement is not elegant and flexible enough. It is simpler and more efficient to use a dictionary to handle multi-condition matching problems in Python. For those who have some experience in Python Players have to admit that this is indeed the case.

But today we will take a look at how to play Switch/Case if we must use Python.

Syntax Constraints

Let’s first define how Switch/Case should be expressed. For simplicity, we can make it look like this.

def cn():
    print('cn')

def us():
    print('us')

switch(lang).case('cn',cn)
            .case('us',us)
               .default(us)
Copy after login

Class implementation one

Through the above constraints, we can implement switch as a class. The incoming parameters are processed in the constructor, and then the case and default methods are implemented respectively. .

class switch(object):
    def __init__(self, case_path):
        self.switch_to = case_path
        self._invoked = False

    def case(self, key, method):
        if self.switch_to == key and not self._invoked:
            self._invoked = True
            method()

        return self

    def default(self, method):
        if not self._invoked:
            self._invoked = True
            method()
Copy after login

In the constructor we remember case_path and execution status _invoked, in case() if the current key matches switch_to and the function has not been executed, then update _invoked and execute the corresponding method. Check _invoked in default(). If it has never been executed, then call the function of the default branch.

It looks pretty good, let’s try it out.

switch('cn').case('cn',cn).case('us',us).default(fail)
>>> cn
switch('us').case('cn',cn).case('us',us).default(fail)
>>> cn
switch('jp').case('cn',cn).case('us',us).default(fail)
>>> fail
switch('cn').case('cn',cn).case('us',us)
>>> cn
Copy after login

Let’s take a look at a few weird cases.

# duplicate case
switch('us').case('us',cn).case('us',us).default(fail)
>>> cn

def cn() return 'cn'
def us() return 'us'

# return value
result = switch('cn').case('cn',cn).case('us',us)
result
>>> <python_switch_case.switch object at 0x11034fb70>
Copy after login

Did you find out? The above implementation will not handle repeated cases. Of course, you can strengthen the case method, preferably by throwing an exception. This is usually done in other programming languages.

The second question is, you want to get the return value from the case. There is no hope in writing it like the above, because it is thrown away. We can consider adding a result variable to the switch class to save the execution results.

class switch(object):
    def __init__(self, case_path):
        ...
        self.result = None

    def case(self, key, method):
        ...
        self.result = method()
    ...
Copy after login

After the call is completed, you can get the result through result.

_ = switch('cn').case('cn',cn).case('us',us)
_.result
>>> cn
Copy after login

Class Implementation 2

I probably searched on the Internet, you can also refer to Brian Beck to implement Swich/Case through classes.

class switch(object):
    def __init__(self, value):
        self.value = value
        self.fall = False

    def __iter__(self):
        """Return the match method once, then stop"""
        yield self.match
        raise StopIteration

    def match(self, *args):
        """Indicate whether or not to enter a case suite"""
        if self.fall or not args:
            return True
        elif self.value in args:
            self.fall = True
            return True
        else:
            return False


c = 'z'
for case in switch(c):
    if case('a'): pass  # only necessary if the rest of the suite is empty
    if case('c'): pass
    # ...
    if case('y'): pass
    if case('z'):
        print("c is lowercase!")
        break
    if case('A'): pass
    # ...
    if case('Z'):
        print("c is uppercase!")
        break
    if case():  # default
        print("I dunno what c was!")
Copy after login

This kind of implementation is relatively complicated, and it is not very comfortable to use. It requires both for and if (it is not as happy as direct if/else). Of course, there are also advantages, that is, cases with the same results can be put together, and more things can be written in the case, not just a method name.

Written at the end

Finally, we have to go back to the method recommended by Python to deal with the switch/case problem. Generally, we can deal with this multi-branch problem through a dictionary, as an example.

MAPPING = {
    'cn': cn,
    'us': us
}

lang = 'cn'
result = MAPPING.get(lang, default=us)
Copy after login

Is it clear at a glance, not only easy to read but also easy to maintain. The key is unique in the dictionary, and the value can be any type of data, either a class or a method, so it is flexible enough.

The above is the detailed content of How to implement switch/case statement in Python. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template