Python函數(shù)參數(shù)全攻略
1.普通參數(shù) (沒有星號(hào))
2.可變位置參數(shù) (*args)
使用單個(gè)星號(hào) *,將多個(gè)位置參數(shù)打包成元組
def func(*nums):
print(f"nums: {nums}, type: {type(nums)}")
func(1, 2, 3) # nums: (1, 2, 3), type: <class 'tuple'>
func('a', 'b') # nums: ('a', 'b'), type: <class 'tuple'>
func() # nums: (), type: <class 'tuple'>python
def calculate_sum(*numbers):
return sum(numbers)
print(calculate_sum(1, 2, 3)) # 6
print(calculate_sum(10, 20, 30, 40)) # 100**3.可變關(guān)鍵字參數(shù) (kwargs)
使用兩個(gè)星號(hào) **,將多個(gè)關(guān)鍵字參數(shù)打包成字典
def func(**nums):
print(f"nums: {nums}, type: {type(nums)}")
func(a=1, b=2, c=3) # nums: {'a': 1, 'b': 2, 'c': 3}, type: <class 'dict'>
func(name="Alice") # nums: {'name': 'Alice'}, type: <class 'dict'>
func() # nums: {}, type: <class 'dict'>def create_user(**user_info):
user = {
'name': 'Unknown',
'age': 0,
'email': ''
}
user.update(user_info) # 用傳入的參數(shù)更新默認(rèn)值
return user
user1 = create_user(name="Alice", age=25)
user2 = create_user(name="Bob", email="bob@example.com")4.混合使用所有參數(shù)類型
def complex_func(required, *args, **kwargs):
print(f"必需參數(shù): {required}")
print(f"可變位置參數(shù): {args}")
print(f"可變關(guān)鍵字參數(shù): {kwargs}")
complex_func("hello", 1, 2, 3, name="Alice", age=25)
# 輸出:
# 必需參數(shù): hello
# 可變位置參數(shù): (1, 2, 3)
# 可變關(guān)鍵字參數(shù): {'name': 'Alice', 'age': 25}5.參數(shù)解包
def func(a, b, c):
print(f"a={a}, b=, c={c}")
# 參數(shù)解包
numbers = [1, 2, 3]
func(*numbers) # 相當(dāng)于 func(1, 2, 3)
params = {'a': 10, 'b': 20, 'c': 30}
func(**params) # 相當(dāng)于 func(a=10, b=20, c=30)def student_info(name, age, *scores, **additional_info):
print(f"學(xué)生: {name}, 年齡: {age}")
print(f"成績: {scores}")
print(f"附加信息: {additional_info}")
# 使用示例
student_info("張三", 20, 85, 90, 78, city="北京", hobby="籃球")
# 輸出:
# 學(xué)生: 張三, 年齡: 20
# 成績: (85, 90, 78)
# 附加信息: {'city': '北京', 'hobby': '籃球'}6.參數(shù)順序規(guī)則:
在函數(shù)定義中,參數(shù)必須按以下順序排列:
普通參數(shù)
*args 參數(shù)
**kwargs 參數(shù)
# 這是錯(cuò)誤的! # def wrong_order(**kwargs, *args, a, b): # pass
到此這篇關(guān)于Python函數(shù)參數(shù)全攻略的文章就介紹到這了,更多相關(guān)Python函數(shù)參數(shù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
2023年最新版Python?3.12.0安裝使用指南(推薦!)
這篇文章主要給大家介紹了關(guān)于2023年最新版Python?3.12.0安裝使用的相關(guān)資料,Python?現(xiàn)在是非常流行的編程語言,當(dāng)然并不是說Python語言性能多么強(qiáng)大,而是Python使用非常方便,特別是現(xiàn)在AI和大數(shù)據(jù)非常流行,用?Python?實(shí)現(xiàn)是非常容易的,需要的朋友可以參考下2023-10-10
Python超參數(shù)優(yōu)化的實(shí)戰(zhàn)方法
在機(jī)器學(xué)習(xí)模型開發(fā)中,超參數(shù)優(yōu)化是提升模型性能的關(guān)鍵環(huán)節(jié),本文聚焦Python超參數(shù)優(yōu)化的實(shí)戰(zhàn)方法,結(jié)合最新工具案例,揭示如何通過科學(xué)調(diào)參實(shí)現(xiàn)模型性能躍升,需要的朋友可以參考下2025-12-12
Python?GUI利用tkinter皮膚ttkbootstrap實(shí)現(xiàn)好看的窗口
這篇文章主要介紹了Python?GUI利用tkinter皮膚ttkbootstrap實(shí)現(xiàn)好看的窗口,文章基于python的相關(guān)資料展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,感興趣的小伙伴可以參考一下2022-06-06
Python實(shí)現(xiàn)比較撲克牌大小程序代碼示例
這篇文章主要介紹了Python實(shí)現(xiàn)比較撲克牌大小程序代碼示例,具有一定借鑒價(jià)值,需要的朋友可以了解下。2017-12-12

