python - 对python函数调用中的**参数感到困惑

标签 python syntax

<分区>

作为引用,我指的是这个 post 中的答案

答案作者给出如下代码

def sum(*values, **options):
    s = 0
    for i in values:
        s = s + i
    if "neg" in options:
        if neg:
            s = -s
    return s

s = sum(1, 2, 3, 4, 5)            # returns 15
s = sum(1, 2, 3, 4, 5, neg=True)  # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15

但是当我在我的机器上运行时,出现以下错误

NameError: global name 'neg' is not defined

谁能解释一下。通常,函数如何知道 values 何时结束以及 options 何时开始

最佳答案

if neg:

那条线有问题。应该是:

if options["neg"]:

How does the function know when values ends and when options begins?

未命名的值放在 *values 中。关键字参数进入 **options

关于python - 对python函数调用中的**参数感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18106256/

相关文章:

javascript - 您可以将 new Date().toUTCString() 更改为自 1970 年 1 月 1 日以来的毫秒数吗?

c++ - 为什么我们将按引用传递的值视为地址?

loops - 如何使用 SPSS LOOP 对同一变量的不同值重复执行命令?

Perl - 错误 "Type of arg 1 to each must be hash (not hash element)"

python - 在 Python 中使用 %s 会去除 CSV 到 XML 转换中的前导零

python - 在 python 3.6 中通过属性表示法表示字典键时的类型提示

python - 构建类以迭代返回的结构

python - 保持 TCP 套接字连接事件和读/写协调

python - 在 Pandas 的一列中模拟 ' '(单引号)?

Cobol 的语法帮助