2.4. switch语句替代方案

2.4.1. 1. 代码示例

#!/usr/bin/env python
#-*- coding:utf8 -*-
from __future__ import division

x =1
y =2

operator = '/'

result = {
    "+": x+y,
    "-": x-y,
    "*": x*y,
    "/": x/y
}

print(result.get(operator, 'wrong value'))


def zero():
    return "zero"

def one():
    return "one"

def switch_case(value):
    switcher = {
        0: zero,
        1: one,
        2: lambda:"tow",
    }

    func = switcher.get(value, lambda :"nothing")
    return func()

print(switch_case(1))
print(switch_case(2))
print(switch_case(3))

2.4.2. 2. 类来实现switch 调度方法

2.1 代码例子

#!/usr/bin/env python
#-*- coding:utf8 -*-
class Switcher(object):
    def numbers_to_methods_to_strings(self, argument):
        """Dispatch method"""
        # prefix the method_name with 'number_' because method names
        # cannot begin with an integer.
        method_name = 'number_' + str(argument)
        # Get the method from 'self'. Default to a lambda.
        method = getattr(self, method_name, lambda: "nothing")
        # Call the method as we return it
        return method()

    def number_0(self):
        return "zero"

    def number_1(self):
        return "one"

    def number_2(self):
        return "two"

hu = Switcher()
for i in range(5):
    print("number_{}:{}".format(i, hu.numbers_to_methods_to_strings(i)))

2.2 代码例子

#!/usr/bin/env python
#-*- coding:utf8 -*-

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: # changed for v1.5, see below
      self.fall = True
      return True
    else:
      return False


# The following example is pretty much the exact use-case of a dictionary,
# but is included for its simplicity. Note that you can include statements
# in each suite.
v = '+'
x = 10
y = 20
for case in switch(v):
    if case('+'):
        print(x+y)
        break
    if case('-'):
        print(x-y)
        break
    if case('*'):
        print(x*y)
        break
    if case('/'):
        print(x/y)
        break
    if case():      #do nothing
        print()
        break
#!/usr/bin/env python
# -*- coding:utf8 -*-
# @auther:   18793
# @Date:    2020/7/6 17:38
# @filename: switch语句.py
# @Email:    1879324764@qq.com
# @Software: PyCharm

def hello():
    return "Hello"


def grrting():
    return "Hello awcloud"


def say_goodbye():
    return "Goodbye, awcloud"


OPERATION = {
    "hello": hello,
    "greeting": grrting,
    "say_goodbye": say_goodbye
}


def switch_function(operation, *args, **kwargs):
    return OPERATION[operation](*args, **kwargs)


if __name__ == '__main__':
    h1 = switch_function("hello")
    print(h1)
    h2 = switch_function("greeting")
    print(h2)