Python Magic Methods Tutorial – Complete Guide

Delve into the enchanting world of Python, where codes and commands take on a mystical aura with the concept of magic methods. In the realm of Python programming, magic methods breathe life into objects, making them respond to common operations in a unique manner, turning your coding journey into a spellbinding adventure.

What Are Python Magic Methods?

Commonly referred to as dunder methods, Python magic methods are special methods with double underscores at the beginning and end of their names. They are designed to create a rich, intuitive syntax for operating with objects in a Pythonic way.

These methods aren’t called magic without a reason. Magic methods allow us to define the behavior of an object. From setting a value to an object to deciding how it should respond when added to another object, everything is under your command with Python magic methods.

Imagine creating a game, where each character responds differently to different environments or power-ups. With Python’s magic methods, not only can you customize their responses, but you can also make the writing and reading of the code incredibly intuitive. To a beginner, this makes Python an exciting language to learn, and to an expert, it opens up a new dimension of clever programming techniques.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Examples of Python Magic Methods

Let’s begin our magical journey into the land of Python Magic methods:

__init__ Method

The __init__ method is called when an object is created. This allows us to set attributes for the object at the time of its creation.

class Potion:
    def __init__(self, type):
        self.type = type

potion_of_strength = Potion('strength')
print(potion_of_strength.type) # Output: strength

__str__ Method

We use the __str__ method to tell Python how to represent an object as a string. This can provide crucial information when debugging.

class Potion:
    def __init__(self, type):
        self.type = type
    def __str__(self):
        return f'A potion of {self.type}'

potion_of_strength = Potion('strength')
print(potion_of_strength) # Output: A potion of strength

__add__ Method

The __add__ method allows us to define what happens when we add two objects together.

class Potion:
    def __init__(self, type):
        self.type = type
    def __add__(self, other):
        return f'Combining a potion of {self.type} and a potion of {other.type}'

potion_of_strength = Potion('strength')
potion_of_wisdom = Potion('wisdom')
print(potion_of_strength + potion_of_wisdom) # Output: Combining a potion of strength and a potion of wisdom

__len__ Method

The __len__ method tells Python how to compute the “length” of an object. This can mean different things for different types of objects.

class Potion:
    def __init__(self, type, potency):
        self.type = type
        self.potency = potency
    def __len__(self):
        return self.potency

potion_of_strength = Potion('strength', 10)
print(len(potion_of_strength)) # Output: 10

More Fascinating Python Magic Methods

Let’s continue unveiling the magic with a few more exciting and useful examples of Python magic methods:

__eq__ Method

The __eq__ method allows us to tell Python how to compare two objects for equality.

class Potion:
    def __init__(self, type):
        self.type = type
    def __eq__(self, other):
        return self.type == other.type

potion_of_strength1 = Potion('strength')
potion_of_strength2 = Potion('strength')
potion_of_wisdom = Potion('wisdom')
print(potion_of_strength1 == potion_of_strength2) # Output: True
print(potion_of_strength1 == potion_of_wisdom) # Output: False

__getitem__ and __setitem__ Methods

The __getitem__ and __setitem__ methods allow us to use indexing syntax with our objects. They are called when we get or set a value with an index, respectively.

class Potion:
    def __init__(self, ingredients):
        self.ingredients = ingredients
    def __getitem__(self, index):
        return self.ingredients[index]
    def __setitem__(self, index, value):
        self.ingredients[index] = value

potion = Potion(['snake venom', 'bat wing', 'dragon scale'])
print(potion[1]) # Output: bat wing
potion[2] = 'unicorn hair'
print(potion[2]) # Output: unicorn hair

__iter__ Method

The __iter__ method tells Python how to make an object iterable, so we can use it in a for loop or other contexts that expect an iterable.

class Potion:
    def __init__(self, ingredients):
        self.ingredients = ingredients
    def __iter__(self):
        return iter(self.ingredients)

potion = Potion(['snake venom', 'bat wing', 'dragon scale'])
for ingredient in potion:
    print(ingredient)
# Output: snake venom
# bat wing
# dragon scale

__call__ Method

The __call__ method allows our objects to be called like functions! It is executed when we call the object just like we would a function.

class Potion:
    def __init__(self, type):
        self.type = type
    def __call__(self):
        return f'Drinking a potion of {self.type}'

potion_of_strength = Potion('strength')
print(potion_of_strength()) # Output: Drinking a potion of strength

__del__ Method

The __del__ method is called when an object is about to be destroyed. This allows us to perform any necessary cleanup.

class Potion:
    def __init__(self, type):
        self.type = type
    def __del__(self):
        print(f'The potion of {self.type} has been used up')

potion_of_strength = Potion('strength')
del potion_of_strength # Output: The potion of strength has been used up

Where To Go Next?

Now that you’ve discovered the magical world of Python’s magic methods, it’s time to think about your next steps on this exciting learning journey. Look no further than our Python Mini-Degree.

This comprehensive collection of courses at Zenva Academy covers various topics, from the basics of Python programming to the complex algorithms, object-oriented programming, game development, and app development.

While learning with us, you will create numerous projects, including tangible games and apps, gaining practical experience and building a solid portfolio that you can showcase to your current or future employers. Our curriculum is designed to be flexible and accessible anytime, which allows you to learn at your own pace.

For a broader array of knowledge, check out our full suite of Python courses. Each course is meticulously created to help you hone multiple facets of Python programming, offering a balanced mix of theoretical understanding and practical implementation.

Conclusion

As you delve deeper into the mystical world of Python, remember that its enchantments are a result of consistent practice and exploration. Thanks to Python’s magic methods, coding can be as thrilling as conjuring spells. Leverage these methods to turn your programming journey into a delightful adventure.

Embark on this magical journey with Zenva’s Python Mini-Degree, where you’ll not only uncover more secrets of Python magic methods but also explore various other exceptional facets of Python. Let us be your guide in mastering these useful skills, shaping a brighter future with every line of code you write.

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.