I've been reading up on python's special class methods in Dive into Python, and it seems like some methods have odd or inconsistent syntax.
To get the items from a dictionary you would call the dictionary class method items()
>>> my_dictionary.items()
[('name', 'Old Gregg'), ('Race', 'Scaly Man-Fish')]
However, to determine the number of keys in that dictionary you would call len()
and supply it with the dictionary as an argument.
>>> len(my_dictionary)
2
I always assumed that methods like len()
weren't actually part of whatever class you called them on given their syntax but after reading chapter 5 of Dive into Python I see that len()
actually does result in a dictionary method being called.
my_dictionary.__len__()
So why isn't it and methods like it called like a typical class method?
my_dictionary.len()
Is there a convention I'm unaware of?
Guido van Rossum explained it thusly:
(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()
. 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.
We are not in the Java world.
There are a lot of methods in Python that are applicable to object if they implement the related API
len() --> __len__()
str() --> __str__()
repr() --> __repr__()
Apart from that:
Why should
my_dictionary.len()
be a method?
In Javascript objects expose their size through the 'length' attribute which is more natural than using a method....sorry, but not all nonsense coming from the Java world is good and must be available in other languages.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With