Python的正常参数与关键字参数 [英] Python normal arguments vs. keyword arguments

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

问题描述

是如何关键字参数,从常规的参数有什么不同?不能所有的参数为名称=值传递的而不是使用位置语法?

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

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

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