Python 中的函数“/”参数

我注意到一些带有/参数的函数签名。可以在以下位置找到这方面的示例collections.Counter.__init__()


    def __init__(self, iterable=None, /, **kwds):

        '''Create a new, empty Counter object.  And if given, count elements

        from an input iterable.  Or, initialize the count from another mapping

        of elements to their counts.

        >>> c = Counter()                           # a new, empty counter

        >>> c = Counter('gallahad')                 # a new counter from an iterable

        >>> c = Counter({'a': 4, 'b': 2})           # a new counter from a mapping

        >>> c = Counter(a=4, b=2)                   # a new counter from keyword args

        '''

        super().__init__()

        self.update(iterable, **kwds)

我无法找到它的用途,当我尝试在本地复制它时,我得到一个SyntaxError.


任何关于它是什么以及为什么使用它的信息将不胜感激。


慕姐8265434
浏览 176回答 2
2回答

慕田峪7331174

PEP570 中描述的新语法:使用“/”表示某些函数参数必须按位置指定(即,不能用作关键字参数)。因此,将通过其位置传递的第一个参数与传递给字典的其余参数分开。

陪伴而非守候

它是 Python 3.8 中的新功能。/ 之前的所有参数都是位置参数,不能使用关键字指定。在上面给出的示例中,写 . 不再合法Counter(iterable=(1,2,3))。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python