模式匹配python版: 不同于java的swith-case 和 scala的match-case, Python里面没有这类关键字. 所以只能通过字典实现: 先定义一个字典以确定映射关系,再通过get('key')方法获取到字典里面对应的值, 值可以是之前定义过的函数或者其他数据类型),最后调用函数并传参,由函数的代码完成运算
============python代码开始============
#encoding:utf-8
# PYTHON中的类库称为模块,实际上每个模块就是个.py文件
from __future__ import print_function
# 和scala语法一样,可以在任意位置导入模块
from __future__ import division
def add(x,y,*tp,**dic):
return x+y
def sub(x,y, *tp, **dic):
return x-y
def mul(x,y, *tp, ** dic):
return x*y
def div(x, y, *tp, **dic):
return x/y # division模块保证:x/y不是整除,而是数学中的除法,即1/8等于0.125而不是0
# *tp表示把冗余的参数存放到元祖tp里面, **dic表示把多出来的字典类型参数放到字典型的dic里面
def power(x,y,*tp, **dic):
print("redundant args(tp):",tp)
print("redundant args(dic):",dic)
return x**y
direct_add = add(1, 2, 3, 4, 5, "abcde", "hello")
print("直接调用add结果:" + str(direct_add))
# 定义一个字典,字典dict是python的内置数据类型,相当于java中的Map,都能用来表示映射关系
# 以运算符作key, 以对应的计算函数作value
ops = {"+":add,
"-":sub,
"*": mul,
"/":div,
"**":power
}
# 传入冗余参数,查看python中如何接收
res0 = ops.get("**")(1, 2, 3, 4, 5, "abcde", "hello",{0:"zero", 'one':1})
print ("1的2次方:%s" % res0)
res1 = ops.get("/")(1,2,)
print ("匹配 / 结果: ",res1)
res2 = ops.get('*')(1, 2)
print("匹配 * 结果:",res2)
res3 = ops['+'](1,2)
print ("匹配加法结果: ",res3)
operator = '-'
res4 = ops.get(operator)(1, 2)
print ("匹配减法结果: ",res4)
============python代码结束============
运行上述python脚本,控制台输出内容如下:
直接调用add结果:3
redundant args(tp): (3, 4, 5, 'abcde', 'hello', {0: 'zero', 'one': 1})
redundant args(dic): {}
1的2次方:1
匹配 / 结果: 0.5
匹配 * 结果: 2
匹配加法结果: 3
匹配减法结果: -1