Magic methods

By 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.

See also

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

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest