为什么这行得通?
尽管函数定义了关键字参数,但函数test接受位置参数。
>>> def test(a=[]):
... print(a)
...
>>> test([1,2,3])
[1, 2, 3]
为什么这行得通?
尽管函数定义了关键字参数,但函数test接受位置参数。
>>> def test(a=[]):
... print(a)
...
>>> test([1,2,3])
[1, 2, 3]
如果您在调用中不提供关键字,则它基本上只是一个位置参数(例如顺序很重要),但如果您不提供值,则具有默认值。但是, * 可以像 in 一样test_2用于强制执行仅关键字参数。
def test_1(a=[], b=1): print(f'a = {a}, b = {b}')
def test_2(*, a=[]): print(a)
def test_3(x, y): print(x, y)
test_1([1, 2, 3])
a = [1, 2, 3], b = 1
test_1(2, [1, 2, 3])
a = 2, b = [1, 2, 3] # order of arguments matter.
test_1(b=2, a=[1, 2, 3])
a = [1, 2, 3], b = 2 # order of arguments does not matter.
test_2('a')
test_2() takes 0 positional arguments but 1 was given
test_3(y='a', x='b') # order does not matter
b a
test_3('a', 'b') # order matters
a b
更新(以防有人通过谷歌搜索或其他方式来到这里):