Python makes extensive use duck typing. This means that when we deal with objects in our code, we are often less concerned with what type of object it is, we really only need to know if it can do certain things.
Under the hood, Python uses various magic methods to implement duck typing. These methods have special names - the begin and end in double underscores, for example
__len__. For this reason they are sometimes called dunder methods (double underscore, geddit?).
The great thing is that we can implement these magic methods in our own classes, to create new types that can interact with the Python interpreter in all sorts of useful ways. It is almost like being able to extend the language itself.
def print_len(x): print(len(x))
This function accepts an object
x and prints that object's length. We know that the built-in function
len works with various types of object - strings, lists and tuples for example. We also know that
len doesn't work with other types of objects, for example you can't find the
len of an integer.
In fact, what
len actually does is to check whether
x implements the
__len__ method (strings, lists, tuples do, integers don't). It then calls the method if it is available, or raises a
TypeError if not.
That is great news, because it means that if we create a class that implements
__len__, it will work the
len function automatically, and that means it will also work with our
There are quite few magic methods and they allow you to control a lot of aspects of how your classes behave. You can:
These are covered in detail in the rest of the articles in this section.
Copyright (c) Axlesoft Ltd 2020