Python 默認值參數



一、問題

定義有默認參數的函數。



二、解決方案

直接在函數定義中給參數指定默認值。

def test(a, b=2):
	print(a, b)
test(1)
test(1, 3)

輸出:

1 2
1 3


默認參數是可修改的容器,如:列表、字典、集合,可以用 None 作為默認值。

def test(a, b=None):
    if b is None:
        return None
    else:
        return []

print(test(1, None))
print(test(1, []))

輸出:

None
[]


最好不要用if not b:代替if b is None:

因為在if not b:中,當b是長度為0的字符串、列表、元組、字典時,也會返回 None。所以會將輸入為0、[], (), {} 當成沒有輸入。

def test(a, b=None):
    if not b:
        return None
    else:
        return []
print(test(1, None))
print(test(1, []))

輸出:

None
None


並不想提供一個默認值,僅測試默認參數是不是傳進來。

測試參數是否被傳遞進來,不能 None、0、False值,因為這些值都是合法的,需要創建一個獨一無二的私有對象實例。如:object 類的實例 object()

_no_value = object()
def test(a, b=_no_value):
    if b is _no_value:
        print('b值沒有傳進來。')
    else:
        print(b)

test(1)
test(1, None)

輸出:

b值沒有傳進來。
None

傳遞一個 None 值和不傳值兩種情況不同。



三、討論

默認參數的值僅在函數定義的時候賦值一次。

x = 2
def test(a, b=x):
    print(a, b)
test(1)

x = 3
test(1)

輸出:

1 2
1 2

改變 x 的值對默認參數值沒影響,因為在函數定義的時候已經確定了它的默認值。



默認參數的值是不可改變的對象。

def test(a, b=[]):
    return b

t = test(1)
print(t)

t.append(2)
t.append('wangke')
print(t)

輸出:

[]

[2, 'wangke']

上面示例,b 的默認值是可改變對象,對 b 進行修改,下次調用這個函數默認值會改變。

為避免這種情況,將默認值設為 None。




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM