一文掌握Python函數(shù)進(jìn)階:參數(shù)類型與返回值
一、函數(shù)參數(shù)的五種類型
Python 函數(shù)的參數(shù)分為五類,按聲明順序依次為:
1. 位置參數(shù)(Positional Arguments)
2. 默認(rèn)參數(shù)(Default Arguments)
3. 可變位置參數(shù)(*args)
4. 關(guān)鍵字參數(shù)(Keyword Arguments)
5. 可變關(guān)鍵字參數(shù)(**kwargs)
1.1 位置參數(shù)(必傳參數(shù))
位置參數(shù)是最常見的參數(shù)形式,調(diào)用時(shí)必須按定義順序傳遞,且數(shù)量必須匹配。
python
def greet(name, message):
? ? print(f"{message}, {name}!")
greet("Alice", "Hello") ? # Hello, Alice!
greet("Bob") ? ? ? ? ? ? ?# TypeError: missing 1 required positional argument1.2 默認(rèn)參數(shù)
在定義時(shí)給參數(shù)賦予默認(rèn)值,調(diào)用時(shí)可以不傳遞該參數(shù)。默認(rèn)參數(shù)必須放在位置參數(shù)之后。
python
def greet(name, message="Hello"):
? ? print(f"{message}, {name}!")
greet("Alice") ? ? ? ? ? # Hello, Alice!
greet("Bob", "Hi") ? ? ? # Hi, Bob!注意:默認(rèn)參數(shù)在函數(shù)定義時(shí)計(jì)算,且只計(jì)算一次。如果默認(rèn)參數(shù)是可變對象(如列表、字典),多次調(diào)用會(huì)共享該對象。
python def add_item(item, lst=[]): ? # 不推薦 ? ? lst.append(item) ? ? return lst print(add_item(1)) ? # [1] print(add_item(2)) ? # [1, 2] 共享了同一個(gè)列表! # 推薦寫法 def add_item(item, lst=None): ? ? if lst is None: ? ? ? ? lst = [] ? ? lst.append(item) ? ? return lst
1.3 可變位置參數(shù)(*args)
*args用于接收任意數(shù)量的位置參數(shù),并將它們打包成一個(gè)元組。args是約定名稱,可以改為其他名字,但*必不可少。
python def sum_all(*args): ? ? return sum(args) print(sum_all(1, 2, 3, 4)) ? # 10 print(sum_all()) ? ? ? ? ? ? # 0
應(yīng)用場景:當(dāng)不確定傳入多少個(gè)參數(shù)時(shí)使用,如數(shù)學(xué)計(jì)算、裝飾器等。
1.4 關(guān)鍵字參數(shù)
調(diào)用時(shí)使用 key=value形式傳遞的參數(shù),可以不按順序。但必須在所有位置參數(shù)之后傳遞。
python
def describe_person(name, age, city):
? ? print(f"{name} is {age} years old and lives in {city}.")
describe_person("Alice", city="New York", age=25) ? # 合法1.5 可變關(guān)鍵字參數(shù)(**kwargs)
**kwargs用于接收任意數(shù)量的關(guān)鍵字參數(shù),并將它們打包成一個(gè)字典。kwargs是約定名稱,**必不可少。
python
def print_info(**kwargs):
? ? for key, value in kwargs.items():
? ? ? ? print(f"{key}: {value}")
print_info(name="Alice", age=25, city="New York")1.6 參數(shù)組合順序
在函數(shù)定義中,參數(shù)必須按以下順序聲明:
位置參數(shù) → 默認(rèn)參數(shù) → *args → 關(guān)鍵字參數(shù)(僅限Python 3) → **kwargs
示例:
python
def complex_func(a, b=1, *args, c, d=2, **kwargs):
? ? print(f"a={a}, b=, args={args}, c={c}, d=wppm3vysvbp, kwargs={kwargs}")
complex_func(10, 20, 30, 40, c=50, d=60, e=70, f=80)
# a=10, b=20, args=(30, 40), c=50, d=60, kwargs={'e': 70, 'f': 80}二、參數(shù)傳遞的細(xì)節(jié)
2.1 傳值還是傳引用?
Python 的參數(shù)傳遞是對象引用傳遞。簡單說:如果傳入的是不可變對象(如整數(shù)、字符串),函數(shù)內(nèi)部修改會(huì)創(chuàng)建新對象,不影響外部;如果傳入的是可變對象(如列表、字典),函數(shù)內(nèi)部修改會(huì)影響外部。
python def modify(x, lst): ? ? x += 1 ? ? ? ? ?# 不可變對象,x指向新對象 ? ? lst.append(4) ? # 可變對象,原列表被修改 a = 10 b = [1,2,3] modify(a, b) print(a) ? ?# 10 print(b) ? ?# [1,2,3,4]
2.2 使用 * 和 ** 解包參數(shù)
在調(diào)用函數(shù)時(shí),可以用 * 解包列表、元組為位置參數(shù),用 **解包字典為關(guān)鍵字參數(shù)。
python
def add(a, b, c):
? ? return a + b + c
nums = [1, 2, 3]
print(add(*nums)) ? ? ? ? ?# 6
kwargs = {'a': 10, 'b': 20, 'c': 30}
print(add(**kwargs)) ? ? ? # 60三、函數(shù)返回值詳解
3.1 單個(gè)返回值
函數(shù)可以使用return返回任意類型的值。如果沒有return或只有return,默認(rèn)返回None。
python def square(x): ? ? return x ** 2 result = square(5) ? # 25
3.2 多個(gè)返回值
Python 函數(shù)可以返回多個(gè)值,實(shí)際上返回的是一個(gè)元組,可以自動(dòng)解包。
python def get_stats(numbers): ? ? return min(numbers), max(numbers), sum(numbers) / len(numbers) min_val, max_val, avg = get_stats([1, 2, 3, 4, 5]) print(min_val, max_val, avg) ? # 1 5 3.0
3.3 返回函數(shù)(閉包)
函數(shù)可以作為返回值,形成閉包,保留外部函數(shù)的變量。
python def make_multiplier(n): ? ? def multiplier(x): ? ? ? ? return x * n ? ? return multiplier times2 = make_multiplier(2) times3 = make_multiplier(3) print(times2(5)) ? # 10 print(times3(5)) ? # 15
3.4 返回生成器(yield)
使用 yield可以讓函數(shù)返回一個(gè)生成器對象,實(shí)現(xiàn)惰性求值,節(jié)省內(nèi)存。
python def count_up_to(n): ? ? i = 1 ? ? while i <= n: ? ? ? ? yield i ? ? ? ? i += 1 for num in count_up_to(5): ? ? print(num) ? # 1 2 3 4 5
四、進(jìn)階技巧
4.1 使用類型提示(Type Hints)
Python 3.5+ 支持類型注解,提高代碼可讀性和 IDE 支持。
python
def greet(name: str, age: int = 18) -> str:
? ? return f"{name} is {age} years old."4.2 強(qiáng)制關(guān)鍵字參數(shù)
在 *之后的參數(shù)必須使用關(guān)鍵字傳遞,避免歧義。
python
def person_info(name, *, age, city):
? ? print(f"{name}, {age}, {city}")
person_info("Alice", age=25, city="NYC") ? # 正確
# person_info("Alice", 25, "NYC") ? ? ? ? ?# 錯(cuò)誤4.3 參數(shù)與返回值的文檔
使用 docstring 清晰描述參數(shù)和返回值。
python def divide(a: float, b: float) -> float: ? ? """ ? ? 返回 a 除以 b 的結(jié)果。 ? ? 參數(shù): ? ? ? ? a (float): 被除數(shù) ? ? ? ? b (float): 除數(shù) ? ? 返回: ? ? ? ? float: 商 ? ? 異常: ? ? ? ? ZeroDivisionError: 當(dāng) b 為 0 時(shí)拋出 ? ? """ ? ? return a / b
五、總結(jié)
位置參數(shù): def f(a, b), 必須按順序傳入
默認(rèn)參數(shù): def f(a, b=1)可選,定義時(shí)求值
可變位置參數(shù): def f(*args), 接收多個(gè)位置參數(shù),打包為元組
關(guān)鍵字參數(shù): def f(a, *, b), * 后必須用關(guān)鍵字傳遞
可變關(guān)鍵字參數(shù): def f(**kwargs), 接收多個(gè)關(guān)鍵字參數(shù),打包為字典
到此這篇關(guān)于一文掌握Python函數(shù)進(jìn)階:參數(shù)類型與返回值的文章就介紹到這了,更多相關(guān)Python參數(shù)類型與返回值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python函數(shù)定義、參數(shù)、返回值與作用域示例詳解
- python之plt.hist函數(shù)的輸入?yún)?shù)和返回值的用法解釋
- C#調(diào)用Python程序傳參數(shù)獲得返回值
- Python生成器傳參數(shù)及返回值原理解析
- Python學(xué)習(xí)筆記之函數(shù)的參數(shù)和返回值的使用
- Python 函數(shù)用法簡單示例【定義、參數(shù)、返回值、函數(shù)嵌套】
- Python 中的參數(shù)傳遞、返回值、淺拷貝、深拷貝
- python3 http提交json參數(shù)并獲取返回值的方法
- 對python3 中方法各種參數(shù)和返回值詳解
相關(guān)文章
pytorch實(shí)現(xiàn)CNN卷積神經(jīng)網(wǎng)絡(luò)
這篇文章主要為大家詳細(xì)介紹了pytorch實(shí)現(xiàn)CNN卷積神經(jīng)網(wǎng)絡(luò),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-02-02
Python基于stuck實(shí)現(xiàn)scoket文件傳輸
這篇文章主要介紹了Python基于stuck實(shí)現(xiàn)scoket文件傳輸,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-04-04
使用Python和OpenCV進(jìn)行視覺圖像分割的代碼示例
在圖像處理領(lǐng)域,圖像分割是一項(xiàng)基礎(chǔ)且關(guān)鍵的技術(shù),它涉及到將圖像劃分為若干個(gè)具有特定屬性的區(qū)域,本文將通過一個(gè)實(shí)踐項(xiàng)目,展示如何使用Python編程語言,結(jié)合OpenCV庫,對一張玫瑰花的圖片進(jìn)行圖像分割,需要的朋友可以參考下2025-01-01
使用Python holidays庫獲取中國節(jié)日的代碼示例
在軟件開發(fā)中,處理節(jié)假日信息是一個(gè)常見需求,尤其是在進(jìn)行日期計(jì)算、日程安排和自動(dòng)化工作流時(shí),Python 提供了一個(gè)名為??holidays??的庫,它能夠輕松獲取節(jié)假日信息,本文將重點(diǎn)介紹如何使用??holidays??庫獲取中國的節(jié)日,并提供詳細(xì)的代碼示例和應(yīng)用場景2024-07-07
淺談python str.format與制表符\t關(guān)于中文對齊的細(xì)節(jié)問題
今天小編就為大家分享一篇淺談python str.format與制表符\t關(guān)于中文對齊的細(xì)節(jié)問題,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-01-01
Pytho爬蟲中Requests設(shè)置請求頭Headers的方法
這篇文章主要介紹了Pytho爬蟲中Requests設(shè)置請求頭Headers的方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-09-09

