list.__len__() or len(list)
Terry Reedy
tjreedy at udel.edu
Wed May 14 13:48:14 EDT 2008
"Nikhil" <mnikhil at gmail.com> wrote in message
news:g0ev6o$utb$1 at registered.motzarella.org...
| Then why to have __len__() internal method at all when the built-in
| len() is faster?
Nearly all syntax constructions and builtin functions are implemented by
calling one or another of the __special__ methods. This is what makes
Python code so generic and plugging your own classes into the system so
easy.
For example, collection[key] = value is implemented by calling
collection.__setitem__(key, value). When you define a class with that
method, that syntax will work with its instances just the same as for
builtin classes.
Similarly, a+b is implemented by calling a.__add__(b). So if a class
defines __add__, you can 'add' its instances (whatever 'add' means for that
class) with '+'.
(The fact that an *implementation* may followup the 'as if' rule and
optimize operations for certain classes by combining steps does not negate
the *language* rules given above.)
tjr
More information about the Python-list
mailing list