标签归档:named-parameters

普通参数与关键字参数

问题:普通参数与关键字参数

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

How are “keyword arguments” different from regular arguments? Can’t all arguments be passed as name=value instead of using positional syntax?


回答 0

有两个相关的概念,都称为“ 关键字参数 ”。

在调用方(这是其他评论者提到的),您可以通过名称指定一些函数自变量。您必须在所有不带名称的参数(位置参数)之后提及它们,并且对于所有根本没有提及的参数,都必须有默认值

另一个概念是在函数定义方面:您可以定义一个按名称接受参数的函数-甚至不必指定这些名称是什么。这些是纯关键字参数,不能按位置传递。语法是

def my_function(arg1, arg2, **kwargs)

您传递给此函数的所有关键字参数都将放入名为的字典中kwargs。您可以在运行时检查此字典的键,如下所示:

def my_function(**kwargs):
    print str(kwargs)

my_function(a=12, b="abc")

{'a': 12, 'b': 'abc'}

There are two related concepts, both called “keyword arguments“.

On the calling side, which is what other commenters have mentioned, you have the ability to specify some function arguments by name. You have to mention them after all of the arguments without names (positional arguments), and there must be default values for any parameters which were not mentioned at all.

The other concept is on the function definition side: you can define a function that takes parameters by name — and you don’t even have to specify what those names are. These are pure keyword arguments, and can’t be passed positionally. The syntax is

def my_function(arg1, arg2, **kwargs)

Any keyword arguments you pass into this function will be placed into a dictionary named kwargs. You can examine the keys of this dictionary at run-time, like this:

def my_function(**kwargs):
    print str(kwargs)

my_function(a=12, b="abc")

{'a': 12, 'b': 'abc'}

回答 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'}

这些功能很少使用,但有时它们非常有用,并且重要的是要知道哪些参数是位置参数或关键字。

There is one last language feature where the distinction is important. Consider the following function:

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

The *positional argument will store all of the positional arguments passed to foo(), with no limit to how many you can provide.

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

The **keywords argument will store any keyword arguments:

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

And of course, you can use both at the same time:

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

These features are rarely used, but occasionally they are very useful, and it’s important to know which arguments are positional or keywords.


回答 2

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

def foo(bar, baz):
    pass

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

Using keyword arguments is the same thing as normal arguments except order doesn’t matter. For example the two functions calls below are the same:

def foo(bar, baz):
    pass

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

回答 3

位置参数

他们前面没有关键字。顺序很重要!

func(1,2,3, "foo")

关键字参数

他们在前面有关键字。它们可以是任何顺序!

func(foo="bar", baz=5, hello=123)

func(baz=5, foo="bar", hello=123)

您还应该知道,如果您使用默认参数并且忽略插入关键字,那么顺序将很重要!

def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)

Positional Arguments

They have no keywords before them. The order is important!

func(1,2,3, "foo")

Keyword Arguments

They have keywords in the front. They can be in any order!

func(foo="bar", baz=5, hello=123)

func(baz=5, foo="bar", hello=123)

You should also know that if you use default arguments and neglect to insert the keywords, then the order will then matter!

def func(foo=1, baz=2, hello=3): ...
func("bar", 5, 123)

回答 4

有两种方法可以将参数值分配给函数参数。

  1. 按位置。位置参数没有关键字,而是首先分配的。

  2. 按关键字。关键字参数具有关键字,并且在位置参数之后排在第二位。

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

如果不使用位置参数,那么-是的- 编写的所有内容实际上都是关键字参数。

调用一个函数您对使用位置或关键字或混合物的决定。您可以根据需要选择所有关键字。我们中有些人没有做出选择,而是使用位置参数。

There are two ways to assign argument values to function parameters, both are used.

  1. By Position. Positional arguments do not have keywords and are assigned first.

  2. By Keyword. Keyword arguments have keywords and are assigned second, after positional arguments.

Note that you have the option to use positional arguments.

If you don’t use positional arguments, then — yes — everything you wrote turns out to be a keyword argument.

When you call a function you make a decision to use position or keyword or a mixture. You can choose to do all keywords if you want. Some of us do not make this choice and use positional arguments.


回答 5

令我感到惊讶的是,似乎没有人指出可以像这样通过字典来传递形式参数的键参数参数。

>>> def func(a='a', b='b', c='c', **kwargs):
...    print 'a:%s, b:%s, c:%s' % (a, b, c)
... 
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>> 

I’m surprised that no one seems to have pointed out that one can pass a dictionary of keyed argument parameters, that satisfy the formal parameters, like so.

>>> def func(a='a', b='b', c='c', **kwargs):
...    print 'a:%s, b:%s, c:%s' % (a, b, c)
... 
>>> func()
a:a, b:b, c:c
>>> func(**{'a' : 'z', 'b':'q', 'c':'v'})
a:z, b:q, c:v
>>> 

回答 6

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

如果彼此之间有许多相似的参数,尤其是当它们属于同一类型时,这会有所帮助,在这种情况下,我更喜欢使用命名参数,或者如果参数属于同一类,则我会创建一个自定义类。

Using Python 3 you can have both required and non-required keyword arguments:


Optional: (default value defined for param ‘b’)

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

Required (no default value defined for param ‘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'`

This can help in cases where you have many similar arguments next to each other especially if they are of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.


回答 7

令我惊讶的是,没有人提到您可以使用*argsand **kwargs从此站点)混合使用位置参数和关键字参数来进行类似的事情:

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

这使您可以使用任意关键字参数,这些参数可能包含您不想预先定义的键。

I’m surprised no one has mentioned the fact that you can mix positional and keyword arguments to do sneaky things like this using *args and **kwargs (from this site):

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

This allows you to use arbitrary keyword arguments that may have keys you don’t want to define upfront.


回答 8

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

I was looking for an example that had default kwargs using type annotation:

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

example:

>>> 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 {}

回答 9

只是补充/添加一种方法来定义调用函数时未在关键字中分配的参数默认值

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

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

Just suplement/add a way for defining the default value of arguments that is not assigned in key words when calling the function:

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

call this by:

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

you’ll get:

default_msg
love

read more about *args and **kwargs in python: https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3