解释 Python 中的仅关键字参数 (VarArgs) [英] Explain Keyword-Only Arguments (VarArgs) in Python

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

问题描述

请看下面的代码:-

#!/usr/bin/python# 文件名:total.pydef total(initial=5, *numbers, **keywords):计数 = 初始对于数字中的数字:计数 += 数量对于关键字的关键:计数 += 关键字[键]返回计数打印(总计(10、1、2、3,蔬菜=50,水果=100))

有人可以解释一下 *numbers 和 **keywords 是如何获得参数的吗?一个简单的解释是非常赞赏提前致谢

解决方案

在您的代码中 numbers 被分配了 (1,2,3) 元组.keywords 被分配一个字典,包含 vegetablesfruits.

一颗星 (*) 定义位置参数.这意味着您可以接收任意数量的参数.您可以将传递的参数视为元组.

两颗星 (**) 定义关键字参数.

参考资料可在此处获得.

示例

Python 2.x(在仅关键字参数之前)

def foo(x, y, foo=None, *args): 打印 [x, y, foo, args]foo(1, 2, 3, 4) -->[1, 2, 3, (4, )] # foo == 4foo(1, 2, 3, 4, foo=True) -->类型错误

Python 3.x(仅带关键字参数)

def foo(x, y, *args, foo=None): print([x, y, foo, args])foo(1, 2, 3, 4) -->[1, 2, None, (3, 4)] # foo 是 Nonefoo(1, 2, 3, 4, foo=True) -->[1, 2, 真, (3, 4)]def combo(x=None, *args, y=None): ... # 2.x 和 3.x 样式在一个函数中

虽然经验丰富的程序员理解 2.x 中发生的事情,但它是违反直觉的(只要有足够的位置参数,位置参数就会绑定到 foo= 与关键字参数无关)

Python 3.x 通过 PEP-3102(varargs 后的关键字参数只能通过名称绑定)

Please see the code below:-

#!/usr/bin/python
# Filename: total.py

def total(initial=5, *numbers, **keywords):
    count = initial
    for number in numbers:
        count += number
    for key in keywords:
        count += keywords[key]
    return count

print(total(10, 1, 2, 3, vegetables=50, fruits=100))

Can someone please explain how is *numbers and **keywords picking up the arguments? A simple explaination is very much appreciayed Thanks in advance

In your code numbers is assigned the (1,2,3) tuple. keywords is assigned a dictionary, containing vegetables and fruits.

One star (*) defines positional arguments. This means that you can receive any number of arguments. You can treat the passed arguments as a tuple.

Two stars (**) define keywords arguments.

The reference material is available here.

Examples

Python 2.x (before keyword-only arguments)

def foo(x, y, foo=None, *args): print [x, y, foo, args]

foo(1, 2, 3, 4)            --> [1, 2, 3, (4, )]  # foo == 4
foo(1, 2, 3, 4, foo=True)  --> TypeError

Python 3.x (with keyword-only arguments)

def foo(x, y, *args, foo=None): print([x, y, foo, args])

foo(1, 2, 3, 4)           --> [1, 2, None, (3, 4)]  # foo is None
foo(1, 2, 3, 4, foo=True) --> [1, 2, True, (3, 4)]

def combo(x=None, *args, y=None): ...  # 2.x and 3.x styles in one function

Although a seasoned programmer understands what happened in 2.x, it's counter-intuitive (a positional argument gets bound to foo= regardless of keyword arguments as long as there are enough positional arguments)

Python 3.x introduces more intuitive keyword-only arguments with PEP-3102 (keyword arguments after varargs can only be bound by name)

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

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