开发者

python: what is this funny notation? [0,1,3].__len__()

  1. why would anyone use double underscores
  2. why not开发者_运维技巧 just do len([1,2,3])?

my question is specifically What do the underscores mean?


__len__() is the special Python method that is called when you use len().

It's pretty much like str() uses __str__(), repr uses __repr__(), etc. You can overload it in your classes to give len() a custom behaviour when used on an instance of your class.

See here: http://docs.python.org/release/2.5.2/ref/sequence-types.html:

__len__(self)
Called to implement the built-in function len(). Should return the length of the object, an integer >= 0.
Also, an object that doesn't define a __nonzero__() method and whose __len__() method returns zero is considered to be false in a Boolean context.


The one reason I've had to use x.__len__() rather than len(x) is due to the limitation that len can only return an int, whereas __len__ can return anything.

You might quite reasonably argue that only an integer should be returned, but if the length of your object is greater than sys.maxsize then you have no choice except to return a long instead:

>>> class A(object):
...     def __len__(self):
...         return 2**80
...
>>> a = A()
>>> len(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: long int too large to convert to int
>>> a.__len__()
1208925819614629174706176L

This isn't just a theoretical limitation, I've done a fair bit of work with bit containers where (with 32-bit Python) the len function stops working when the object reaches just 256MB.


If you "absolutely must" call it as a method (rather than a function) then the double underscores are needed. But the only motivation I can think for the code you show of is that somebody's gone so OO-happy that they don't understand the key Python principle that you don't directly call special methods (except you may need to call your superclass's version if you're overriding it, of course) -- you use the appropriate builtin or operator, and it calls (internally) whatever special methods are needed.

Actually, in the code you show the only sensible thing is to just use the constant 3, so maybe you've oversimplified your example a little...?-)


You should read the docs on special method names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜