本文介绍了普通参数与关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关键字参数"与常规参数有何不同?不能将所有参数都以name=value的形式传递,而不是使用位置语法吗?

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

推荐答案

有两个相关概念,都称为"关键字参数".

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)

您传递给此函数的任何关键字参数都将放入名为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'}

这篇关于普通参数与关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 10:41
查看更多