Magic methods
Magic methods are special methods that are automatically called when certain operations are performed on an object. They are always surrounded by double underscores (e.g. __init__
).
They are also called dunder methods (short for double underscore). We can use them to define how operators behave on our objects. For example, we can define how to add two objects together or how to compare two objects. They are very useful when we want to override the default behavior of an operator or function.
Here’s a list of some of the most common magic methods:
🪄 Magic method 🪄 | Description |
---|---|
__init__ |
Constructor |
__str__ |
String representation of an object |
__repr__ |
String representation of an object |
__add__ |
Addition operator |
__sub__ |
Subtraction operator |
__mul__ |
Multiplication operator |
__truediv__ |
Division operator |
__eq__ |
Equality operator |
__lt__ |
Less than operator |
__gt__ |
Greater than operator |
__le__ |
Less than or equal to operator |
__ge__ |
Greater than or equal to operator |
__len__ |
Length operator |
__getitem__ |
Get item operator |
__setitem__ |
Set item operator |
__delitem__ |
Delete item operator |
__contains__ |
Contains operator |
__call__ |
Call operator |
How to override magic methods
Here’s an example of a class that overrides the __print__
, __add__
and __eq__
magic methods. This might be useful if we want to print a custom message when we print an object or if we want to add two objects together in a custom way.
class Beam:
def __init__(self, length, height, width):
self.length = length
self.height = height
self.width = width
def __print__(self):
"""Override the print function"""
print(f"Beam object with length: {self.length}, height: {self.height}, width: {self.width}")
def __add__(self, other):
"""Override the addition operator"""
# check if the other object is of the same type
if isinstance(other, Beam):
# create a new beam with the sum of the lengths
new_beam = Beam(self.length + other.length, self.height, self.width)
return new_beam
else:
raise TypeError("Can only add two Beam objects together")
def __eq__(self, other):
"""Override the equality operator"""
# check if the other object is of the same type
if isinstance(other, Beam):
# check if the beams have the same length
if self.length == other.length:
return True
else:
return False
else:
raise TypeError("Can only compare two Beam objects together")
How to use magic methods
Here’s how we can use the defined magic methods after we created an instance of the Beam
class:
# Create an instance of the Beam class
my_beam_A = Beam(10, 0.2, 0.2)
my_beam_B = Beam(20, 0.2, 0.2)
my_beam_C = Beam(10, 0.2, 0.2)
# print the beam
print(my_beam_A) # Beam object with length: 10, height: 0.2, width: 0.2
# add two beams together
my_beam_D = my_beam_A + my_beam_B
print(my_beam_D.length) # 30
# compare two beams
print(my_beam_A == my_beam_C) # True
🛠 Exercise
01:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍
Solution:
01:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02:🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍