Web Developer

Python Object Oriented Programming | Magic Methods

Magic methods are special methods which have double underscores at the beginning and end of their names. They are known as dunders. They are used to create functionality that can’t be represented as a normal method.

One common use of them is operator overloading. This means defining operators for custom classes that allow operators such as + and * to be used on them.

The __add__ method allows for the definition of a custom behavior for the + operator in our class. As you can see, it adds the corresponding attributes of the objects and returns a new object, containing the result. Once it’s defined, we can add two objects of the class together.

More magic methods for common operators:

The __sub__ for - The __mul__ for * The __truediv__ for / The __floordiv__ for // The __mod__ for % The __pow__ for ** The __and__ for & The __xor__ for ^ The __or__ for |

The expression x + y is translated into x.__add__(y). However, if x hasn’t implemented __add__, and x and y are of different types, then y.__radd__(x) is called. There are equivalent r methods for all magic methods just mentioned.

As you can see, you can define any custom behavior for the overloaded operators.

There are several magic methods for making classes act like containers.

The __len__ for len() The __getitem__ for indexing The __setitem__ for assigning to indexed values The __delitem__ for deleting indexed values The __iter__ for iteration over objects The __contains__ for in