Python正常参数vs.关键字参数。

时间:2022-03-05 23:23:36

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

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

8 个解决方案

#1


276  

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:

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

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

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

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

#2


148  

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()的所有位置参数,不限制您可以提供的数量。

>>> 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.

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

#3


85  

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)

#4


33  

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)

#5


20  

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.

当你调用一个函数时,你决定使用位置或关键字或混合。如果你想,你可以选择做所有的关键字。我们中的一些人不会做出这样的选择并使用位置参数。

#6


18  

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

#7


12  

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

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

Optional: (default value defined for 'b')

可选:(为“b”定义的默认值)

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

Required (no default value defined for 'b'):

要求(没有为“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 a many similar arguments next to each other especially when of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.

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

#8


10  

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):

我很惊讶没有人提到,你可以将位置和关键字的参数组合在一起,使用*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])

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

这允许您使用任意的关键字参数,这些参数可能有您不想预先定义的键。

#1


276  

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:

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

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

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

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

#2


148  

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()的所有位置参数,不限制您可以提供的数量。

>>> 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.

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

#3


85  

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)

#4


33  

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)

#5


20  

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.

当你调用一个函数时,你决定使用位置或关键字或混合。如果你想,你可以选择做所有的关键字。我们中的一些人不会做出这样的选择并使用位置参数。

#6


18  

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

#7


12  

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

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

Optional: (default value defined for 'b')

可选:(为“b”定义的默认值)

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

Required (no default value defined for 'b'):

要求(没有为“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 a many similar arguments next to each other especially when of the same type, in that case I prefer using named arguments or I create a custom class if arguments belong together.

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

#8


10  

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):

我很惊讶没有人提到,你可以将位置和关键字的参数组合在一起,使用*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])

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

这允许您使用任意的关键字参数,这些参数可能有您不想预先定义的键。