普通参数与关键字参数 [英] Normal arguments vs. keyword arguments

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

问题描述

关键字参数"与常规参数有何不同?不能将所有参数都作为 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'}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆