gpt4 book ai didi

Python2 : arguments after *argv

转载 作者:行者123 更新时间:2023-11-30 23:15:29 26 4
gpt4 key购买 nike

我发现 py2 和 py3 之间有奇怪的区别

请看一段代码: https://github.com/DoumanAsh/collectionScripts/blob/master/python/art/trace.py#L101

当我尝试在 py2 中使用此方法导入类时:

from trace import EventTracer3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "trace.py", line 101
def trace(self, event, *argv, frame=None):

SyntaxError: invalid syntax

但是对于py3来说没问题。我无法找到 py2 中函数参数是否有任何限制...这实际上有点奇怪,因为据我所知,python2 和 python3 在函数声明方面不应该有任何差异。我是错还是对?

最佳答案

有意为之,并有记录。请参阅the Python 2 grammar :

parameters: '(' [varargslist] ')'
varargslist: ((fpdef ['=' test] ',')*
('*' NAME [',' '**' NAME] | '**' NAME) |
fpdef ['=' test] (',' fpdef ['=' test])* [','])

...所以,您可以使用逗号分隔的常规参数,后跟 *NAME*NAME、**NAME**NAME ——这必须是参数列表的末尾。

您还可以看到Python 2 tutorial kwargs 的描述:

When a final formal parameter of the form **name is present, [...]

...添加了强调;在 Python 2 中,kwargs 必须是列表中的最后一个参数。

<小时/>

Python 3.0 引入 PEP 3102 ,它添加了仅关键字参数,可以跟随可变参数列表;这就是您的示例代码所使用的。

关于Python2 : arguments after *argv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28226457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com