This question already has answers here:
What does the slash mean in help() output?

(3个答案)


去年关闭。





看起来很基本,但是由于它本身与python语言有关,我在这里感到迷茫。
根据Python 3.6文档:

>>>help(sum)

...
sum(iterable, start=0, /)
    Return the sum of a 'start' value (default: 0) plus an iterable of numbers
...


当我呼叫:sum([0,1,2], start=1)时,我得到:

TypeError: sum() takes no keyword arguments


这里发生了什么?

最佳答案

原型is a convention that means that all arguments prior to it are positional only中的/;它们不能通过关键字传递。用Python定义的函数不能做到这一点(至少,不仅要接受*args中的参数并手动解包内容,尽管链接的PEP建议也允许使用Python级别函数的语法),但是由于sum是使用C实现的内置函数可以做到这一点(实际上是在内部进行手动拆包,但是可以播发更有用的原型),并且更容易定义默认值。不接受关键字自变量允许它比允许关键字自变量更有效地运行。

关键是,该参数的名称不是真正的start,因此您不能按名称传递该参数。您必须按位置传递它,例如:

sum([0,1,2], 1)

关于python - Python 3.6 sum()是否具有“start = 0”关键字参数? ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53877574/

10-12 01:37
查看更多