Why len (list) instead of list.len () in python?

Maybe a strange question. But I scratched my head, why, if you want to get the length of the list, you cannot just say list.len (), and you need to pass the list to len () to get its size? And where does this len () actually occur?

+4
source share
2 answers

You can get the length of a large number of items. Lists, voice recorders, sets, other collections. So builtin len() , which calls type(obj).__len__(obj) internally, gives you the standard API to get the length.

If all of these collection types had a len() method that was called directly, there would be nothing to stop anyone from creating their own collection class that uses, for example. .length() or .length .

Here is an explanation from Guido van Rossum, the creator of Python:

First of all, I chose len(x) for x.len() for HCI reasons ( def __len__() came much later). There are actually two related reasons: and HCI:

(a) For some operations, prefix notation is better read than postfix - prefix (and infix!) operations have a long tradition in mathematics, which loves notes in which the mathematician thinks about a problem. Compare the ease with which we rewrite a formula like x*(a+b) in x*a + x*b for awkwardness by doing the same thing using raw OO notation.

(b) When I read the code that says len(x) , I know that it asks for the length of something. This tells me two things: the result is integer, and the argument is some kind of container. Otherwise, when I read x.len() , I should already know that x is a kind of container that implements an interface or inherits from a class that has the standard len() . Witness the confusion we sometimes have when a class that does not implement a mapping has a get() or keys() method or something that is not a file has a write() method.

Saying the same thing differently, I see "len" as an inline operation. I would love to lose this. I can’t say for sure whether you mean it or not, but β€œdef len (self): ...” seems like you want to downgrade it to the usual method. I'm very -1 on this.

+10
source

it really comes from __len__() :

 In [15]: lis=[1,2,3] In [16]: lis.__len__() Out[16]: 3 

object.__len__(self) :

Called to implement the built-in len () function. Must return the length of the object, an integer> = 0. In addition, an object that does not define a nonzero () method and the len () method returns zero is considered false in a Boolean context.

+5
source

Source: https://habr.com/ru/post/1445516/


All Articles