具有关键字参数的Python函数接受位置参数

时间:2020-05-20 20:10:24

标签: python-3.x

为什么这样做?

函数test接受位置参数,尽管该函数定义了关键字参数。

>>> def test(a=[]):
...  print(a)
... 
>>> test([1,2,3])
[1, 2, 3]

2 个答案:

答案 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

更新(以防有人通过谷歌搜索或其他方式来到这里)

Argument = / = Parameter

答案 1 :(得分:2)

在Python中,* args和/(PEP570)之前的参数可用作位置参数和关键字参数。 在您的情况下,您必须这样写才能强制将a作为关键字参数。

>>> def test(*args,a=[]):
...  print(a)
... 
>>> test([1,2,3])
[]
>>> test(a=[1,2,3])
[1, 2, 3]

有关更多信息,您可以阅读此python doc

相关问题