Magic methods


Martin McBride, 2018-10-14
Tags duck typing
Categories magic methods
In section Python language



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):
    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.

<<Prev

Tag cloud

2d arrays abstract data type alignment and array arrays bezier curve built-in function close closure colour comparison operator comprehension context conversion data types design pattern device space dictionary duck typing efficiency encryption enumerate filter font font style for loop function function composition function plot functools generator gif gradient greyscale higher order function html image processing imagesurface immutable object index inner function input installing iter iterator itertools lambda function len linspace list list comprehension logical operator lru_cache mandelbrot map monad mutability named parameter numeric python numpy object open operator optional parameter or partial application path positional parameter print pure function radial gradient range recipes recursion reduce rgb rotation scaling sequence slice slicing sound spirograph str stream string subpath symmetric encryption template text text metrics transform translation transparency tuple unpacking user space vectorisation webserver website while loop zip

Copyright (c) Axlesoft Ltd 2020