iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0

lambda expression

python可以使用lambda expression宣告匿名函式,但目前還不清楚在甚麼樣的情境下需要使用。只知道可以當作另一個function的回傳值。

add_five = lambda x: x + 5
print( "{}".format(add_five(10)) )
print( "type of lambda expression: {}".format(lambda x: x + 5) )

# 15
# type of lambda expression: <function <lambda> at 0x7f40fbc4a8c8>


def make_adder(n):
    return lambda x: x + n

add_three = make_adder(3)
add_thirty = make_adder(30)

print( "{}".format(add_three(10)) )
print( "type of lambda expression add_three: {}".format(add_three) )

print( "{}".format(add_thirty(10)) )
print( "type of lambda expression add_thirty: {}".format(add_thirty) )

# 13
# type of lambda expression add_three: <function make_adder.<locals>.<lambda> at 0x7f40fbc4a730>
# 40
# type of lambda expression add_thirty: <function make_adder.<locals>.<lambda> at 0x7f40fbc4a950>

decorator expression

恩,Don't Reinvent Sandwich: Decorator是目前看到最清楚且完整的說明和範例了!結論是decorator是一種重複利用頭尾的機制。

參考


上一篇
Day18-Function-Argument語法糖
下一篇
Day20-Function-Variable Scope
系列文
if len(learning.python) == 30:31

尚未有邦友留言

立即登入留言