這篇文章是閱讀Asabeneh的30 Days Of Python: Day 11 - Functions後的學習筆記與心得。
Python中使用def
關鍵字(keyword)來宣告(declare)函式:
def greetings():
print("Hello!")
# 呼叫函式
greetings() # 'Hello!'
print(greetings()) # None
None
。def greetings(name):
return f"Hello {name}!"
print(greetings("John")) # 'Hello John!'
呼叫(calling)函式時給進括弧中的數值,會稱為引數(argument)
透過這種方式,參數(parameter)撰寫的順序不會影響到引數傳入的順序:
def deco_sentence(word1, word2):
print(f"✨${word1} ${word2}✨")
deco_sentence("30days", "Python")
# ✨30days Python✨
deco_sentence(word2 = "30days", word1 = "Python")
# ✨Python 30days✨
✨30days Python✨
宣告函式時可以給參數指定預設值,如果呼叫函式時沒有給該參數,就會使用該預設值;跟在JS差不多:
def greetings(name = "World"):
return f"Hello {name}!"
print(greetings("John")) # 'Hello John!'
print(greetings()) # 'Hello World!'
? 注意!跟JS不同,Python中函式一旦被創造出來,每次呼叫的函式都會是同一個物件,也就會產生下面這個例子的狀況:
def greetings(name_lst = [], ):
name_lst.append("Hello")
print(name_lst)
greetings() # ['Hello']
greetings() # ['Hello', 'Hello']
greetings() # ['Hello', 'Hello', 'Hello']
詳細的說明可以參考這個回答
當不確定要接受的參數的數目有多少個,可以在參數名稱前加上*
;效果就像JS中的其餘參數(rest parameter):
def greetings(*names):
name_list = ""
names_quantity = len(names)
for i in range(names_quantity):
if i == names_quantity - 1:
name_list = name_list + names[i]
continue
name_list = name_list + names[i] + ", "
return f"Hello {name_list}!"
print(greetings("John", "Mary", "Becky"))
# Hello John, Mary, Becky!
就像JS,我們也可以把函式當參數傳入另一個函式中:
def join_list(lst, separator=","):
end = len(lst)
r = ""
for i in range(end):
if i != end - 1:
r += lst[i] + separator + " "
else:
r += lst[i]
return r
def greetings(cb, *names):
name_list = cb(names)
print("Hello " + name_list + "!")
greetings(join_list, "John", "Mary", "Becky")