我知道python有一个len()函数,用于确定字符串的大小,但我想知道为什么它不是字符串对象的方法?


当前回答

met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.

其他回答

met% python -c 'import this' | grep 'only one'
There should be one-- and preferably only one --obvious way to do it.

这里的其他答案中遗漏了一些东西:len函数检查__len__方法是否返回一个非负整型。len是一个函数的事实意味着类不能重写此行为以避免检查。因此,len(obj)提供了obj.len()无法提供的安全级别。

例子:

>>> class A:
...     def __len__(self):
...         return 'foo'
...
>>> len(A())
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    len(A())
TypeError: 'str' object cannot be interpreted as an integer
>>> class B:
...     def __len__(self):
...         return -1
... 
>>> len(B())
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    len(B())
ValueError: __len__() should return >= 0

当然,可以通过将len函数重新赋值为全局变量来“覆盖”它,但是这样做的代码显然比覆盖类中的方法的代码更可疑。

吉姆对这个问题的回答可能会有所帮助;我复制在这里。引用Guido van Rossum的话:

First of all, I chose len(x) over x.len() for HCI reasons (def __len__() came much later). There are two intertwined reasons actually, both HCI: (a) For some operations, prefix notation just reads better than postfix — prefix (and infix!) operations have a long tradition in mathematics which likes notations where the visuals help the mathematician thinking about a problem. Compare the easy with which we rewrite a formula like x*(a+b) into x*a + x*b to the clumsiness of doing the same thing using a raw OO notation. (b) When I read code that says len(x) I know that it is asking for the length of something. This tells me two things: the result is an integer, and the argument is some kind of container. To the contrary, when I read x.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standard len(). Witness the confusion we occasionally have when a class that is not implementing a mapping has a get() or keys() method, or something that isn’t a file has a write() method. Saying the same thing in another way, I see ‘len‘ as a built-in operation. I’d hate to lose that. /…/

字符串确实有一个length方法:__len__()

Python中的协议是在具有长度的对象上实现这个方法,并使用内置的len()函数为你调用它,类似于在可迭代的对象上实现__iter__()并使用内置的iter()函数(或在幕后为你调用该方法)。

有关更多信息,请参见模拟容器类型。

这里有一篇关于Python协议主题的很好的阅读:Python和最小惊讶原则

有一个len方法:

>>> a = 'a string of some length'
>>> a.__len__()
23
>>> a.__len__
<method-wrapper '__len__' of str object at 0x02005650>