What are Magic Methods in Python Classes? (45/100 Days of Python)
Python allows developers to create custom classes. In addition to the standard methods and attributes, Python classes also provide a set of special methods known as “magic methods” or “dunder methods” (short for “double underscore methods”). These methods are used to control the behavior of the class and its objects, and they can be used to define custom operations for the class, such as addition, comparison, and iteration.
Magic Methods Overview
Magic methods in Python classes are denoted by a double underscore prefix and a double underscore suffix. For example, the method for defining the behavior of the + operator is called __add__
. The magic methods are called automatically by the Python interpreter when a specific operation is performed on an object of the class. Here are some of the most commonly used magic methods in Python classes:
__init__
: This method is called when an object of the class is created. It is used to initialize the attributes of the class.__str__
: This method is called when thestr()
function is applied to an object of the class. It is used to return a string representation of the object.__len__
: This method is called when thelen()
function is applied to an object of the class. It is used to return the length of the object.__add__
: This method is called when the + operator is applied to two objects of the class. It is used to define the behavior of the addition operator for the class.__eq__
: This method is called when the == operator is applied to two objects of the class. It is used to define the behavior of the equality operator for the class.__iter__
: This method is called when theiter()
function is applied to an object of the class. It is used to make the object iterable.
Using Magic Methods in Python Classes
Now that we have a basic understanding of magic methods in Python classes, let’s take a look at how they can be used in practice. Consider the following example where we define a class called Person
:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f'Person(name={self.name}, age={self.age})'
In this example, we have defined two magic methods: __init__
and __str__
. The __init__
method is used to initialize the name
and age
attributes of the class, and the __str__
method is used to return a string representation of the object. Let’s create an object of the Person
class and see how it behaves:
person = Person('John Doe', 30)
print(person)
# Person(name=John Doe, age=30)
As you can see, the __str__
method is automatically called when we print the person
object, and it returns the string representation of the object.
Let’s take another example where we define a custom class that implements the addition operator:
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f'Vector({self.x}, {self.y})'
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
return Vector(x, y)
In this example, we have defined a class called Vector
that represents a two-dimensional vector. The __init__
method is used to initialize the x
and y
attributes of the vector, the __str__
method is used to return a string representation of the vector, and the __add__
method is used to define the behavior of the addition operator for the class. Let’s create two vectors and add them:
vector1 = Vector(1, 2)
vector2 = Vector(3, 4)
vector3 = vector1 + vector2
print(vector3) # Vector(4, 6)
As you can see, the __add__
method is automatically called when we add two vectors, and it returns a new vector that is the sum of the two vectors.
What’s next?
- If you found this story valuable, please consider clapping multiple times (this really helps a lot!)
- Hands-on Practice: Free Python Course
- Full series: 100 Days of Python
- Previous topic: Mastering Private and Protected Fields in Python Classes: A Complete Tutorial
- Next topic: Inheritance