在第16天的文章提到了函式 Function
,大概講過基本概念後知道了函式可以把程式碼封裝起來,讓邏輯更加模組化以及增加重複使用性,但 Python 中函式可不只有這樣,函式本身不僅能『執行』,還能夠『回傳』——這就是所謂的『高階函式』,它能夠讓我們以『函式當作變數』的方式來操作,實現簡潔、抽象化的程式設計。
在 Python 中函式屬於一等公民,允許對函式進行以下操作:
舉個例子:
在這個例子中,apply()
方法屬於高階函式,因為它接受函式func
作為參數,而square()
方法只是一個普通的函式,但當它被傳入apply()
方法後,讓apply()
可以套用不同的邏輯,這樣的設計可以應付各種邏輯,不必寫死在函式內部。
def apply(func, value):
return func(value)
def square(x):
return x * x
print(apply(square, 5)) # 25
有提到函式可被賦值給變數
,在 Python 中函式的本質上是『物件』,因此能像是變數一樣被儲存和傳遞。
def person(name):
return f"我是{name}。"
hello = person
print(hello("小明")) # 我是小明
當希望『方法』是彈性的時候,就可以把函式當作參數傳入。
從以下例子得知calculate()
方法不需要具體的知道是加法或是乘法,只要接受一個函式即可。
def calculate(func, x, y):
return func(x, y)
def add(x, y):
return x + y
def mul(x, y):
return x * y
print(calculate(add, 4, 3)) # 7
print(calculate(mul, 2, 4)) # 8
以下來介紹幾個常見的高階函式:
map
:map(func, iterable)
將函式func
套用到可迭代的物件每個元素上,並回傳新的結果。numbers = [1, 2, 3]
squares = map(lambda x: x**2, numbers)
print(list(squares)) # [1, 4, 9]
filter
:filter(func, iterable)
根據條件函式func
篩選符合條件的元素。numbers = [1, 2, 3]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) [2]
reduce
:reduce(func, iterable)
需要做引入才能夠使用,將函式不斷做序列元素累積成單一結果。from functools import reduce
numbers = [1, 2, 3]
product = reduce(lambda x, y: x * y, numbers)
print(product) # 6
sorted
:sorted(func, iterable)
可接受函式key
來當作排序依據。words = ["tomato", "mango", "apple", "banana"]
print(sorted(words, key=len)) # ['mango', 'apple', 'tomato', 'banana']
那麼今天就介紹到這,明天見ㄅㄅ!