Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Magic Methods and Dunder | Python Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. Python Fundamentals

Lesson 29 of 55

·Python

Magic Methods and Dunder

20 minutes

Course progress53%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • `__repr__` defines the official string representation (`repr()`).
  • `__str__` defines the informal string representation (`str()`).
  • `__len__` enables use of `len(obj)`.
  • `__add__`, `__sub__`, etc. support arithmetic operators.

Magic Methods and Dunder

Magic (or dunder) methods are special hooks that let your objects integrate with Python’s built‑in syntax. They always start and end with double underscores (__).

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
    def __repr__(self):
        return f'Vector({self.x}, {self.y})'
    def __len__(self):
        return 2
    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

v1 = Vector(1, 2)
v2 = Vector(3, 4)
print(v1)           # Vector(1, 2)
print(len(v1))      # 2
print(v1 + v2)      # Vector(4, 6)

Implementing the appropriate dunder methods makes your classes feel like native Python types.

Make it stickPractice what you've learned1 quiz · 5 practical tests · Optional activities from Python FundamentalsBrowse activities
Previous lessonOOP – EncapsulationContinue to lesson 30DecoratorsBack to Python Fundamentals curriculum