Magic methods

Martin McBride, 2018-10-14
Tags duck typing
Categories magic methods

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.

Duck typing

For example:

def 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 print_len function.

Magic methods

There are quite few magic methods and they allow you to control a lot of aspects of how your classes behave. You can:

  • Control how your class is displayed by the print function
  • Allow it to take part in for loops like a range or list object
  • Make it indexable like a list
  • Make it callable like a function
  • Define how it behaves when used with operators such as +, -, < etc

These are covered in detail in the rest of the articles in this section.

If you found this article useful, you might be interested in the book Functional Programming in Python or other books by the same author.


Popular tags

2d arrays abstract data type alignment and animation arc array arrays bezier curve built-in function callable object circle classes close closure cmyk colour comparison operator comprehension context context manager conversion creational pattern data types design pattern device space dictionary drawing duck typing efficiency else encryption enumerate fill filter font font style for loop function function composition function plot functools game development generativepy tutorial generator geometry gif gradient greyscale higher order function hsl html image image processing imagesurface immutable object index inner function input installing iter iterable iterator itertools l system lambda function len line linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path polygon positional parameter print pure function pycairo radial gradient range recipes rectangle recursion reduce rgb rotation scaling sector segment sequence singleton slice slicing sound spirograph sprite square str stream string stroke subpath symmetric encryption template text text metrics tinkerbell fractal transform translation transparency tuple turtle unpacking user space vectorisation webserver website while loop zip