python学习笔记 - lambda表达式 . 函数. 作为参数传参

#=============== lambda作为参数 ====================
#函数或lambda表达式作为参数传参
def calculate(x, y, func):
    return func(x, y)

#加法
def add(x, y):
    return x + y

#减法
def sub(x, y):
    return x - y

a,b = 5,8
add_ret = calculate(a, b, add)  #加法
sub_ret = calculate(a, b, sub)  #减法
mul_ret = calculate(a, b, lambda a,b : a*b)  #乘法
dev_ret = calculate(a, b, lambda a,b : a/b)  #除法

print('加法运算: {}+{}={}'.format(a, b, add_ret))
print('减法运算: {}-{}={}'.format(a, b, sub_ret))
print('乘法运算: {}*{}={}'.format(a, b, mul_ret))
print('除法运算: {}/{}={}'.format(a, b, dev_ret))

打印结果:
加法运算: 5+8=13
减法运算: 5-8=-3
乘法运算: 5*8=40
除法运算: 5/8=0.625

 

posted @ 2017-04-20 14:19  C/C++/Python/Java  阅读(3817)  评论(0编辑  收藏  举报