【问题标题】:Function "/" argument in Python [duplicate]Python中的函数“/”参数[重复]
【发布时间】:2020-12-12 12:39:42
【问题描述】:

我注意到一些带有/ 参数的函数签名。这方面的一个例子可以在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

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

【问题讨论】:

    标签: python collections


    【解决方案1】:

    new syntax described at PEP570:使用“/”表示某些函数参数必须按位置指定(即不能用作关键字参数)。
    因此,将按其位置传递的第一个参数与传递给字典的其余参数分开。
    Positional-Only Parameter阅读更多内容。

    【讨论】:

      【解决方案2】:

      这是 Python 3.8 中的新功能。 / 之前的所有参数都是仅位置参数,不能使用关键字指定。

      在上面给出的示例中,写Counter(iterable=(1,2,3)) 不再合法。

      https://docs.python.org/3/whatsnew/3.8.html#positional-only-parameters

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-01
        • 2018-11-12
        • 2018-10-17
        • 2018-10-28
        • 2014-10-13
        • 1970-01-01
        相关资源
        最近更新 更多