前言 :
你設計了一個點餐程式,目前主餐有炸雞,價格為49元 :
- def friedChicken():
- return 49.0
- print(friedChicken()) # 49.0
- def friedChicken():
- return 49.0
- print('Fried Chicken=', friedChicken()) # 49.0
- def sideDish1(meal):
- return lambda: meal() + 30
- friedChicken = sideDish1(friedChicken)
- print('Fried Chicken Dish=',friedChicken()) # 79.0
函式修飾器 :
以上是傳遞函式的一個應用. 在 Python 中,你還可以使用以下的語法 :
- test2.py :
- def sideDish1(meal):
- return lambda: meal() + 30
- @sideDish1
- def friedChicken():
- return 49.0
- print('Fried Chicken Dish=', friedChicken()) # 79
你可以堆疊修飾器,例如 :
- test3.py :
- def sideDish1(meal):
- return lambda: meal() + 30
- def sideDish2(meal):
- return lambda: meal() + 40
- @sideDish2
- @sideDish1
- def friedChicken():
- return 49.0
- print(friedChicken()) # 119.0
- def sideDish1(meal):
- return lambda: meal() + 30
- def sideDish2(meal):
- return lambda: meal() + 40
- def friedChicken():
- return 49.0
- friedchicken = sideDish2(sideDish1(friedChicken))
- print(friedchicken()) # 119.0
- @deco('param')
- def func():
- pass
- func = deco('param')(func)
- test4.py :
- def sideDish(number):
- return {
- 1 : lambda meal: (lambda: meal() + 30),
- 2 : lambda meal: (lambda: meal() + 40),
- 3 : lambda meal: (lambda: meal() + 50),
- 4 : lambda meal: (lambda: meal() + 60)
- }.get(number, lambda meal: (lambda: meal()))
- @sideDish(2)
- @sideDish(3)
- def friedChicken():
- return 49.0
- print('Side Dish3+2=', friedChicken()) # 139.0
- def sidedish(number):
- def dish1(meal):
- return lambda: meal() + 30
- def dish2(meal):
- return lambda: meal() + 40
- def dish3(meal):
- return lambda: meal() + 50
- def dish4(meal):
- return lambda: meal() + 60
- def nodish(meal):
- return lambda: meal()
- return {
- 1 : dish1,
- 2 : dish2,
- 3 : dish3,
- 4 : dish4
- }.get(number, nodish)
- @sidedish(2)
- @sidedish(3)
- def friedchicken():
- return 49.0
- print(friedchicken()) # 139.0
* [Python 學習筆記] 函式、類別與模組 : 函式 (lambda 運算式)
沒有留言:
張貼留言