“关键字参数”与常规参数有何不同?所有的参数不能被传递为name=value而不是使用位置语法吗?


当前回答

使用Python 3,你可以同时拥有必需的和非必需的关键字参数:


可选:(为参数'b'定义的默认值)

def func1(a, *, b=42):
    ...
func1(value_for_a) # b is optional and will default to 42

必需(没有为参数'b'定义默认值):

def func2(a, *, b):
    ... 
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`

这可以帮助在你有许多相似的参数,特别是如果他们是相同类型的情况下,在这种情况下,我更喜欢使用命名参数或我创建一个自定义类,如果参数属于一起。

其他回答

有两种方法将参数值赋给函数形参,这两种方法都被使用。

的位置。位置参数没有关键字,首先被赋值。 通过关键字。关键字参数具有关键字,并且在位置参数之后被赋值。

注意,您可以选择使用位置参数。

如果你不使用位置参数,那么——是的——你写的所有东西都变成了一个关键字参数。

当你调用一个函数时,你决定使用位置或关键字或两者的组合。如果你愿意,你可以选择做所有的关键字。我们中的一些人并没有做出这样的选择,而是使用位置参数。

我正在寻找一个使用类型注释的默认kwargs的示例:

def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
     return ' '.join([a, b, c, str(kwargs)])

例子:

>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}

只需补充/添加一种方法来定义参数的默认值,当调用函数时,这些参数没有在关键字中赋值:

def func(**keywargs):
if 'my_word' not in keywargs:
    word = 'default_msg'
else:
    word = keywargs['my_word']
return word

叫它:

print(func())
print(func(my_word='love'))

你会得到:

default_msg
love

阅读更多关于python中的*args和**kwargs的信息:https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3

使用关键字参数与普通参数是一样的,只是顺序不重要。例如,下面两个函数调用是相同的:

def foo(bar, baz):
    pass

foo(1, 2)
foo(baz=2, bar=1)

还有最后一个重要的语言特性。考虑以下函数:

def foo(*positional, **keywords):
    print "Positional:", positional
    print "Keywords:", keywords

*positional参数将存储传递给foo()的所有位置参数,不限制提供的数量。

>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}

**keywords参数将存储任何关键字参数:

>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}

当然,你可以同时使用这两个词:

>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}

这些特性很少被使用,但偶尔它们非常有用,知道哪些参数是位置参数或关键字是很重要的。