0Pricing
Learn AI with Python · Lesson

Magic Methods (__str__, __repr__, etc.)

Dive into Python's special methods for customizing object behavior.

Magic Methods (__str__, __repr__, etc.) is a free Learn AI with Python lesson on CoddyKit — lesson 6 of 6. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 6 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

Introduction to Magic Methods

Magic methods, also known as dunder methods (short for 'double underscore'), are special methods in Python that enable you to define how objects behave in specific situations.

In this lesson, you’ll learn how to use common magic methods like __str__, __repr__, and others.

Magic Methods (__str__, __repr__, etc.) — illustration 1

2

What Are Magic Methods?

Magic methods are predefined methods in Python that are called automatically when specific operations are performed on objects. They are identified by their double underscores, like __init__ or __str__.

3

The __init__ Method

The __init__ method is a constructor that initializes a new object. It’s called automatically when an object is created:

# Using the __init__ method to initialize attributes
class Person:
    def __init__(self, name, age):
        self.name = name  # Initialize the name attribute
        self.age = age  # Initialize the age attribute

# Creating an instance of Person
person = Person("Alice", 30)
print(person.name, person.age)  # Outputs: Alice 30

4

The __str__ Method

The __str__ method defines the string representation of an object when print() is called:

# Defining the __str__ method
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"Name: {self.name}, Age: {self.age}"  # String representation

person = Person("Alice", 30)
print(person)  # Outputs: Name: Alice, Age: 30

5

The __repr__ Method

The __repr__ method provides an official string representation of an object, often used for debugging:

# Defining the __repr__ method
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"  # Debug-friendly representation

person = Person("Alice", 30)
print(repr(person))  # Outputs: Person('Alice', 30)

6

Overloading Operators with Magic Methods

You can use magic methods to customize the behavior of operators like + or ==:

# Overloading the + operator with __add__
class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Point(self.x + other.x, self.y + other.y)  # Adding two points

    def __str__(self):
        return f"({self.x}, {self.y})"

point1 = Point(1, 2)
point2 = Point(3, 4)
result = point1 + point2  # Calls __add__
print(result)  # Outputs: (4, 6)

7

Commonly Used Magic Methods

Here are some commonly used magic methods:

  • __len__: Defines the behavior of the len() function.
  • __getitem__: Allows indexing like a list or dictionary.
  • __eq__: Customizes the equality comparison using ==.

8

Using __len__ and __getitem__

You can use __len__ to define the length of a custom object and __getitem__ to make it indexable:

# Using __len__ and __getitem__ in a custom class
class CustomList:
    def __init__(self, items):
        self.items = items

    def __len__(self):
        return len(self.items)  # Defines the behavior of len()

    def __getitem__(self, index):
        return self.items[index]  # Enables indexing

custom_list = CustomList([1, 2, 3])
print(len(custom_list))  # Outputs: 3
print(custom_list[1])  # Outputs: 2

9

10

Common Mistakes with Magic Methods

Here are some mistakes to avoid:

  • Defining a magic method without matching its intended behavior.
  • Overloading operators unnecessarily.
  • Forgetting to implement required magic methods in custom data types.

11

What Did We Learn?

In this lesson, you learned:

  • What magic methods are and why they are useful.
  • How to use common magic methods like __init__, __str__, and __repr__.
  • How to overload operators using magic methods.

Great job! Let’s move to the next topic.

Magic Methods (__str__, __repr__, etc.) — illustration 11

Frequently asked questions

Is the “Magic Methods (__str__, __repr__, etc.)” lesson free?

Yes — the full text of “Magic Methods (__str__, __repr__, etc.)” is free to read here on the web, and the Learn AI with Python course includes 6 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.

What will I learn in “Magic Methods (__str__, __repr__, etc.)”?

Dive into Python's special methods for customizing object behavior. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Learn AI with Python?

No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 6 of 6, so you can start here or from the beginning and move at your own pace.

How long does the “Magic Methods (__str__, __repr__, etc.)” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Learn AI with Python lesson?

Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Classes and Objects
  2. Attributes and Methods
  3. Inheritance
  4. Polymorphism
  5. Encapsulation and Abstraction
  6. Magic Methods (__str__, __repr__, etc.)
← Back to Learn AI with Python