在函数定义中使用*参数和关键字

2024-05-14 10:50:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数定义如下:

def test(self, *args, wires=None, do_queue=True):
    pass

在Python3中,它正常运行,但在Python2中,它会因语法错误而崩溃。如何修改它以在Python2中工作?你知道吗


Tags: 函数testselfnonetrue定义queuedef
1条回答
网友
1楼 · 发布于 2024-05-14 10:50:11

在Python2中实现这一点的唯一方法是将仅关键字参数作为**kwargs接受并手动提取它们。python2无法以任何其他方式执行仅关键字的参数;它是a new feature of Python 3 to allow this at all。你知道吗

最接近的Python 2等价物是:

def test(self, *args, **kwargs):
    wires = kwargs.pop('wires', None)
    do_queue = kwargs.pop('do_queue', True)
    if kwargs:
        raise TypeError("test got unexpected keyword arguments: {}".format(kwargs.keys()))

相关问题 更多 >

    热门问题