python - 位置参数与关键字参数

标签 python

基于 this

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 都是位置参数。那为什么我们也可以用关键字参数语法来调用它呢?

最佳答案

你引用的那段文字似乎对两个完全不同的事情感到困惑:

我怀疑将这些课件放在一起的人完全熟悉 Python :-) 因此,您提供的链接质量不是很好。


在您对函数的 调用 中,您使用的是“关键字参数”功能(其中参数被命名而不是依赖于它的位置)。没有它,值将绑定(bind)到仅基于顺序的名称。所以,在这个例子中,下面的两个调用是等价的:

def process_a_and_b(a, b):
   blah_blah_blah()

process_a_and_b(1, 2)
process_a_and_b(b=2, a=1)

进一步举例,引用下面的定义和调用:

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.

关于python - 位置参数与关键字参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9450656/

相关文章:

python - 值错误 : y contains new labels: ['#' ]

python - 如何在 numpy 中将向量乘以数组/矩阵元素?

python - 如何根据另一列的条件对 Pandas 中的一列进行子集化

python - 在 Python 中简化深度字典

python - 如何在python中创建一个可调用的函数数组

python - 如何在 Python 3(0x80 及更高版本)中编写 ANSI 兼容字节?

python - 通过 Python 连接到 Interactive Brokers API

python - 如何使用 ctypes 将 C 函数中返回的二维数组传递给 python

python - 使用 Python FFMPEG 在模板/布局中合并多个视频?

Python文本提取