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


当前回答

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

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

其他回答

我正在寻找一个使用类型注释的默认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 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'}

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

我很惊讶没有人提到你可以混合位置参数和关键字参数,使用*args和**kwargs来做这样的鬼鬼祟祟的事情:

def test_var_kwargs(farg, **kwargs):
    print "formal arg:", farg
    for key in kwargs:
        print "another keyword arg: %s: %s" % (key, kwargs[key])

这允许您使用任意关键字参数,这些参数可能包含您不想在前面定义的键。

使用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'`

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

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

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