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