python-2.7 - python 2.7,具有位置、关键字参数以及可变数量参数(任意参数列表)的函数

标签 python-2.7

有没有一种方法可以实现具有可变数量参数 (*args) 以及非可选关键字参数的函数?我想实现这样的东西:

def foo(positional arguments, keyword arguments,*args):

     {
      ...
     }

不过,现在好像没有办法正确调用这个函数。设 arg1 和 arg2 为我们要在函数调用中传递的类型 (*arg) 的参数。

foo(posargs, kwarg=value, arg1, arg2) 

不允许(kwargs 必须在最后),而:

foo(posargs,arg1,arg2,kwarg=value)

会导致错误的函数调用,因为 arg1 在位置上分配给了 kwarg,尽管在函数调用中为 kwarg 提供了关键字值。

是否有任何替代定义或调用语法可以避免这种情况(除了在函数调用中使用 kwarg 值作为位置参数进行调用的简单解决方案之外)?

最佳答案

这是一个 Python 3 特性,在 PEP 3102 中引入. ( Python, default keyword arguments after variable length positional arguments )

在 Python 2 中,您必须从 **kwargs 中提取关键字参数:

def foo(positional arguments, *args, **kwargs):
    # for a required positional argument
    try:
        kwarg = kwargs.pop('kwarg')
    except KeyError as e:
        raise TypeError('Required positional argument not found', e)

    # or for an optional positional argument
    kwarg = kwargs.pop('kwarg', None)

    if kwargs:
        raise TypeError('Unexpected positional arguments', kwargs)

关于python-2.7 - python 2.7,具有位置、关键字参数以及可变数量参数(任意参数列表)的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38595509/

相关文章:

Python:保存和恢复数据成员的装饰器

python-2.7 - fill_between给出 "ValueError: Argument dimensions are incompatible"

Python:表示返回和参数类型的标准方法

linux - Pygame屏幕闪烁

python-2.7 - Python - 将 TCP 套接字对象传递给多处理队列

python - 每次在 python 中运行脚本时都需要生成一个新的文本文件并保存它

python - 迭代列表时增加变量计数器

python - 系统找不到为 check_output 指定的文件

python - 字典中的百分比?

python - keras 中不兼容的密集层错误