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 readx.len(), I have to already know that x is some kind of container implementing an interface or inheriting from a class that has a standardlen(). Witness the confusion we occasionally have when a class that is not implementing a mapping has aget()orkeys()method, or something that isn’t a file has awrite()method.