有時候預先不知道函數需要接受多少個實參,python允許函數從調用語句中收集任意數量的實參。
"""
這是一個制作比薩的函數,它需要接受很多配料,但無法預先確定顧客要多少種配料
函數中形參名*toppings,"*"功能是創建一個名為toppings的空元組,并將收的的所有值都封裝到這個元組中
"""
def make_pizza(*toppings):
"""打印顧客點的所有配料"""
print(toppings)
make_pizza("peperoni")
make_pizza("mushrooms","green peppers","extra cheese")
運行結果:
>>>
======================== RESTART: D:/python學習/8.5.py ========================
('peperoni',)
('mushrooms', 'green peppers', 'extra cheese')
>>>
現在我們可以用循環語句,對配料表進行遍歷,并對顧客點的比薩進行描述:
"""
這是一個制作比薩的函數,它需要接受很多配料,但無法預先確定顧客要多少種配料
函數中形參名*toppings,"*"功能是創建一個名為toppings的空元組,并將收的的所有值都封裝到這個元組中
"""
def make_pizza(*toppings):
"""打印顧客點的所有配料"""
print("\nMakeing a pizza with the following toppings:")
for topping in toppings:
print("-"+topping)
make_pizza("peperoni")
make_pizza("mushrooms","green peppers","extra cheese")
運行結果:
>>>
======================== RESTART: D:/python學習/8.5.py ========================
Makeing a pizza with the following toppings:
-peperoni
Makeing a pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
>>>
8.5.1 結合使用位置實參和任意數量實參
如果要讓函數接受不同類型的實參,必須在函數定義中將接納任意數量 實參的形參放在最后。python先匹配位置實參和關鍵字實參,再將余下的實參都收集到最后一個形參中。
例如:前面的函數還需要加一個表示比薩尺寸的實參 ,必須將該形參放在形參*toppings的前面。
"""
這是一個制作比薩的函數,它需要接受很多配料,但無法預先確定顧客要多少種配料
函數中形參名*toppings,"*"功能是創建一個名為toppings的空元組,并將收的的所有值都封裝到這個元組中
"""
def make_pizza(size,*toppings):
"""概述要制作的比薩"""
print("\nMakeing a "+str(size)+"-inch pizza with the following toppings:")
for topping in toppings:
print("-"+topping)
make_pizza(16,"peperoni")
make_pizza(12,"mushrooms","green peppers","extra cheese")
運行結果:
>>>
======================== RESTART: D:/python學習/8.5.py ========================
Makeing a 16-inch pizza with the following toppings:
-peperoni
Makeing a 12-inch pizza with the following toppings:
-mushrooms
-green peppers
-extra cheese
>>>
8.5.2 使用任意數量的關鍵字實參
有時候需要接受任意數量任意類型的信息,可將函數編寫成能夠接受任意數量的鍵-值對。
"""函數 build_profile()的定義要求提供名和姓,同時允許用戶根據需要提供任意數量的名稱-值對。
形參**user_info,兩個*的功能是創建一個名為user_info的空字典,并將收集到的所有名稱-對都封裝到這個字典中。
在該函數中可以像訪問其他字典那樣訪問user_info中的名稱-值對。
"""
def build_profile(first,last,**user_info):
"""創建一個字典,其中包含我們知道的有關用戶的一切"""
profile={}
profile["first_name"]=first
profile["last_name"]=last
for key,value in user_info.items():
profile[key]=value
return profile
user_profile=build_profile("albert","einstein",location='princeton',field='physics')
print(user_profile)
運行結果:
>>>
================== RESTART: C:/Users/admin/Desktop/8.5.2.py ==================
{'first_name': 'albert', 'last_name': 'einstein', 'field': 'physics', 'location': 'princeton'}
>>>
說明:返回的字典包含用戶的名、姓,還有求學的地方和所學專業。調用這個函數不管額外提供了多少個鍵-值對都能正確處理
浙公網安備 33010602011771號