0Pricing
Python Academy · Lesson

Magic Methods: __str__ and __repr__

Implement dunder methods for readable object representations.

What Are Magic Methods?

Magic (dunder) methods are special methods with double underscores that Python calls in specific contexts, like printing or comparison.

class Foo:
    def __str__(self):
        return "I am Foo"

f = Foo()
print(f)        # I am Foo
print(str(f))   # I am Foo

__repr__: Developer Representation

__repr__ should return an unambiguous string that ideally allows recreating the object. It is shown in the REPL and used by repr().

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

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

p = Point(3, 4)
print(repr(p))  # Point(3, 4)

All lessons in this course

  1. Classes and the __init__ Method
  2. Instance vs Class Attributes
  3. Instance Methods and self
  4. Magic Methods: __str__ and __repr__
← Back to Python Academy