Chapter 4Magic Methods

Python classes may optionally define a long list of methods that, when defined, are called when the instances of the class are used in certain situations. For example, a class may define under what situations its instances should be considered equivalent by defining a method called __eq__. If the __eq__ method is defined, it is invoked if the class meets an equality test using the == operator.

The purpose of these so-called “magic methods” is to overload Python operators or built-in methods. They are defined using the _ syntax to avoid a case where a programmer accidentally defines a method with the same name without explicitly opting in to the functionality. Magic methods provide consistency between the contracts that built-in classes (including primitives such as integers and strings) provide, as well as the contracts that custom classes provide. If you want to test for equivalence in Python, you should always be able to use == to do so, regardless of whether you are testing two integers, two instances of a class that you wrote for your specific application, or even two instances of unrelated classes.

This chapter explores magic methods, how they work, and what magic methods are available.

Magic Method Syntax

In Python, magic methods follow a consistent pattern—the name of the method is wrapped on both sides by two underscores. For example, when an instance of a class is instantiated, the method that runs is __init__ (not init).

This convention exists ...

Get Professional Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.