+ 3
why __len__ & len() instead of .len()?
its kinda bugging me, why do we need to override a hook method in our own class so it can be used with len() ? my experience with other language make it feels counterintuitive lets not start with class, how about an array/list ? java, javascript, ruby, c# use .length or .Length why python not using len as a method instead ? i mean there's a possibility its used somewhere but doesnt see it as much as __len__ with len() what cause this ? is it the case of "we've been use it since early 2000" ? or other like "people use them all the time" or "its not very pythonic" or "why fix it if its not broken" mind you i'm not critize it, just a curiousity more than anything
5 Antworten
+ 5
Quoting Guido van Rossum:
First of all, I chose len(x) over x.len() for HCI (human-computer interaction) 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 xa + xb 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().
+ 5
continuation:
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
0
thank you everyone for your answer, i get the idea of why
https://www.sololearn.com/discuss/2184568/?ref=app
i just found this thread, kinda have a same question. why count() is a method ? isnt it kinda break the x*(a+b) analogy
0
how can I write a CGPA calculator using ruby