在Python 3.8 Programming FAQ中,我看到了以下函数定义:
class callByRef:
def __init__(self, /, **args):
for key, value in args.items():
setattr(self, key, value)
the Python 3.7 version中缺少此内容:
class callByRef:
def __init__(self, **args):
for (key, value) in args.items():
setattr(self, key, value)
新的/
语法是什么?
它与/
输出中出现的help()
有何关系?
答案 0 :(得分:3)
/
的语法为introduced in Python 3.8。
自变量列表中/
的基本原理在PEP 570 -- Python Positional-Only Parameters中给出:
新语法将使库作者可以进一步控制如何调用其API。它将允许指定哪些参数必须称为仅位置参数,同时防止将它们称为关键字参数。
以前,(信息性的)PEP 457定义了语法,但是作用域更加模糊。该PEP通过证明语法的正确性并为函数定义中的
/
语法提供实现,使原始建议更进一步。
相似之处
出于所有意图和目的,如果您了解help()
的{{1}}表示法,那么这就是通过PEP 570在v3.8中正式包含为Python语法的内容。
差异
/
PEP 570 -- Python Positional-Only Parameters
PEP 457 -- Notation For Positional-Only Parameters
批注中使用的表示法(不是语法) There are already excellent answers on the meaning and usage of /
in arguments。
要为您节省点击次数:
help()
表示所有之前的参数都是仅位置参数。调用函数时,/
之前的仅位置参数不能作为/
传递。
Python 3.8 What's New给出了以下示例:
name=value
有效函数调用:
def pow(x, y, z=None, /):
r = x**y
if z is not None:
r %= z
return r
pow(2, 10)
无效函数调用:
pow(2, 10, 17)
pow(x=2, y=10)