为什么Python代码使用len()函数而不是length方法? [英] Why does Python code use len() function instead of a length method?
问题描述
我知道python具有用于确定字符串大小的len()
函数,但是我想知道为什么它不是字符串对象的方法.
I know that python has a len()
function that is used to determine the size of a string, but I was wondering why it's not a method of the string object.
好吧,我意识到我尴尬地犯了错误. __len__()
实际上是字符串对象的方法.在字符串对象上使用len函数在Python中看到面向对象的代码似乎很奇怪.此外,将__len__
作为名称而不只是len也很奇怪.
Ok, I realized I was embarrassingly mistaken. __len__()
is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see __len__
as the name instead of just len.
推荐答案
字符串确实具有长度方法:__len__()
Strings do have a length method: __len__()
The protocol in Python is to implement this method on objects which have a length and use the built-in len()
function, which calls it for you, similar to the way you would implement __iter__()
and use the built-in iter()
function (or have the method called behind the scenes for you) on objects which are iterable.
有关更多信息,请参见模拟容器类型.
See Emulating container types for more information.
这里是有关Python协议主题的好书: Python和最小惊讶原则
Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment
这篇关于为什么Python代码使用len()函数而不是length方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!