位置论证 vs.关键字参数 [英] Positional argument v.s. keyword argument

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

问题描述

基于这个

位置参数是后面没有等号的名称(=) 和默认值.

A positional argument is a name that is not followed by an equal sign (=) and default value.

关键字参数后跟一个等号和一个表达式给出其默认值.

A keyword argument is followed by an equal sign and an expression that gives its default value.

def rectangleArea(width, height):
    return width * height

print rectangleArea(width=1, height=2)

问题> 我假设 widthheight 都是位置参数.那为什么我们也可以用关键字参数语法来调用它呢?

Question> I assume that both width and height are positional arguments. Then why can we also call it with the keyword argument syntax?

推荐答案

您引用的文本是针对函数的定义,与函数调用无关.在对该函数的调用中,您使用的是命名参数"功能.您提供的链接质量不是很好,作者似乎混淆了两种不同的内容.

That text you quote is for the definition of the function and has nothing to do with calls to the function. In the call to that function, you're using the "named argument" feature. That link you provide is not a very good quality one, the authors seem confused between two different things.

Python 引用仅在调用函数时引用位置和关键字参数(请参阅 部分 5.3.4 调用).

The Python reference refers to positional and keyword arguments only in respect to a call to a function (see section 5.3.4 Calls).

当他们在section 7.6 Function 中讨论函数的定义时定义,这是一个完全不同的术语默认参数值".

When they talk about the definition of a function in section 7.6 Function definitions, it's a totally different term "default parameter values".

我怀疑制作这些课件的人完全不熟悉 Python :-)

I suspect the people who put together that course-ware weren't totally familiar with Python :-)

例如,参考以下定义和调用:

By way of example, refer to the following definition and calls:

def fn (a, b, c = 1):          # a/b required, c optional.
    return a * b + c

print fn (1, 2)                # returns 3, positional and default.
print fn (1, 2, 3)             # returns 5, positional.
print fn (c = 5, b = 2, a = 2) # returns 9, named.
print fn (b = 2, a = 2)        # returns 5, named and default.
print fn (5, c = 2, b = 1)     # returns 7, positional and named.
print fn (8, b = 0)            # returns 1, positional, named and default.

= 的含义会发生变化,具体取决于它是在定义中还是在调用中.

The meaning of the = changes, depending on whether it's in the definition or in the call.

在定义中,它将参数标记为可选并设置默认值.

In the definition, it marks the argument optional and sets a default value.

在调用中,它只允许您指定哪些参数应该是哪些值,以您想要的任何顺序.

In the call, it simply allows you to specify which arguments should be which values, in whatever order you want.

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

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