Introduction

Introduction#

Special Methods are methods which get called by Python’s built-in functions and operators .

For example the following functions call a corresponding special method:

  • print

  • len

  • max

This is a form of polymorphism.

Note

Special methods are also known as: - Magic methods - “Dunder” methods, which is short for “double underscore”

Example

Here’s a concrete example using a Robot class that implements the special method __str__, which is called when using str().

class Robot:

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return "{} is at your service!".format(self.name)


karel = Robot("Karel")

string = str(karel)

print(string)

Writing Special Methods#

Special methods are denoted in Python by names that start and end with a double underscore “__”.

The names of each special method here and in general are of the following form

def __NAME__(self, parameter_1, ..., parameter_n):
    # Perform some actions
    # Optionally return a value

In the example above:

  • __NAME__ is a placeholder name, we must use one of the documented method names in practice

  • parameter_1, ..., parameter_n are some number of parameter that the method might receive, this depends on the specific special method

  • the special method will perform some relevant actions

  • in many cases the method must return a value of a specific type.