Python built-in functions
There are numerous functions in Python that perform a task or calculate a result on certain objects without being methods on the class. Their purpose is to abstract common calculations that apply to many types of classes. This is applied duck typing; these functions accept objects with certain attributes or methods that satisfy a given interface, and are able to perform generic tasks on the object.
Len
The simplest example is the len()
function. This function counts the number of items in some kind of container object such as a dictionary or list. For example:
>>> len([1,2,3,4]) 4
Why don't these objects have a length property instead of having to call a function on them? Technically, they do. Most objects that len()
will apply to have a method called __len__()
that returns the same value. So len(myobj)
seems to call myobj.__len__()
.
Why should we use the function instead of the method? Obviously the method is a special method with double-underscores suggesting...