为什么这样做?
函数test
接受位置参数,尽管该函数定义了关键字参数。
>>> def test(a=[]):
... print(a)
...
>>> test([1,2,3])
[1, 2, 3]
答案 0 :(得分:2)
如果您在通话中不提供关键字,那么它基本上只是一个位置参数(例如订单问题),但是如果您不提供值,则使用默认值。但是,可以像在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
更新(以防有人通过谷歌搜索或其他方式来到这里)
答案 1 :(得分:2)