In Python, magic methods (also known as dunder methods) are special methods that start and end with double underscores (__)
. These methods are used to define behaviour for built-in Python operations, such as arithmetic operations, comparison operations, and type conversions. Here are some commonly used magic methods in Python:
- __init__(self[, args...]) : This method is called when an object is created and is used to initialize the attributes of the object.
- __str__(self) : This method is called when an object is printed using the
print
function. It returns a string representation of the object. - __add__(self, other) : This method is called when the + operator is used to add two objects. It returns the result of the addition.
- __eq__(self, other) : This method is called when the
==
operator is used to compare two objects. It returnsTrue
if the objects are equal, andFalse
otherwise. - __lt__(self, other) : This method is called when the
<
operator is used to compare two objects. It returnsTrue
if the first object is less than the second object, andFalse
otherwise. - __len__(self) : This method is called when the
len
function is used to get the length of an object. It returns the length of the object. - __getitem__(self, key) : This method is called when an item is accessed using the square bracket notation (
[]
). It returns the value of the item at the given key. - __setitem__(self, key, value) : This method is called when an item is assigned a value using the square bracket notation (
[]
). It sets the value of the item at the given key. - __delitem__(self, key) : This method is called when an item is deleted using the
del
keyword and the square bracket notation ([]
). It deletes the item at the given key.
These are just a few examples of the many magic methods available in Python. By using these methods, you can customize the behavior of your classes and make them more intuitive and easier to use. Here is an example of how to use a magic method in Python:
class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def __str__(self):
return f"Rectangle with width={self.width} and height={self.height}"
def __eq__(self, other):
if isinstance(other, Rectangle):
return self.width == other.width and self.height == other.height
return False
def area(self):
return self.width * self.height
In this example, we have defined a Rectangle class that has three methods: __init__
, __str__
, and __eq__
.
The __init__
method is the constructor for the Rectangle
class. It takes two parameters, width
and height
, and initialises the corresponding attributes of the object.
The __str__
method is a magic method that is called when the str
function is used to convert an object to a string. In this case, it returns a string that represents the object in a human-readable format.
The __eq__
method is another magic method that is called when the ==
operator is used to compare two objects. It takes one parameter, other
, and compares the width
and height
attributes of the two objects. If they are equal, it returns True
, otherwise it returns False
.
We have also defined a area
method that calculates the area of the rectangle. Here is an example of how to use this class:
rect1 = Rectangle(5, 10)
rect2 = Rectangle(5, 10)
rect3 = Rectangle(3, 8)
print(rect1) # Output: Rectangle with width=5 and height=10
print(rect1 == rect2) # Output: True
print(rect1 == rect3) # Output: False
print(rect1.area()) # Output: 50
In this example, we have created three Rectangle
objects, rect1
, rect2
, and rect3
, and called the __str__
, __eq__
, and area methods on them. The output shows the results of these operations.