On 06/24/12 10:48, Stefan Behnel wrote: > gmspro, 24.06.2012 10:01: > >> Why are some methods/functions named in this way in python? __len__ >> >> underscoreunderscoreNAMEunderscoreunderscore >> >> Is there any speciality of naming such methods? >> > Yes. Look up "special methods" in the documentation. > > You may have noticed the correspondence between len() and __len__(). That > is Python's way of allowing you to implement this kind of generic > functionality (sometimes referred to as a protocol). > > You also asked why len() is a function instead of a method. Don't you find > it much easier to use one function for everything than to look up and > sometimes even learn one method for each kind of object you are dealing > with? Python prefers simplicity here. You want the length? Use len(). > > Stefan What does this have to do with using a function vs a method?
In the python 2.x series, the iterator protocol, proscribe you need to define a "next" method, which you can call directly or which is called in for statements. Now in python 3.x the method is called "__next__" and there is a next-function which will call this __next__ method. I see no difference in difficulty between item = iter.next() and item = next(iter). Neither do I see a difference in difficulty between size = len(seq) or size = seq.len(). Sure it is possible for someone feeling uncooperative to write a class in which method giving the length of the object was named something different from "len". But that is now also possible. -- http://mail.python.org/mailman/listinfo/python-list