Magic Methods: __str__ and __repr__
Implement dunder methods for readable object representations.
Magic Methods: __str__ and __repr__ is a free Python Academy lesson on CoddyKit — lesson 4 of 4. 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 Python Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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)__str__: User Representation
__str__ provides a human-friendly string. print() and str() call it. If absent, Python falls back to __repr__.
class Temperature:
def __init__(self, celsius):
self.celsius = celsius
def __str__(self):
return f"{self.celsius}°C"
def __repr__(self):
return f"Temperature({self.celsius})"
t = Temperature(100)
print(t) # 100°C
print(repr(t)) # Temperature(100)When Each Is Called
__str__: print(), str(), f-strings. __repr__: REPL, repr(), containers displaying their elements.
class Item:
def __str__(self): return "str"
def __repr__(self): return "repr"
x = Item()
print(x) # str
print([x]) # [repr] ← list uses repr for elements__format__ for Custom Formatting
Define __format__ to control how f-strings with format specs display your object.
class Money:
def __init__(self, amount):
self.amount = amount
def __format__(self, spec):
if spec == "usd":
return f"${self.amount:.2f}"
return str(self.amount)
m = Money(9.5)
print(f"{m:usd}") # $9.50__bool__ for Truthiness
__bool__ lets your object be evaluated in boolean contexts. Return True or False.
class Bag:
def __init__(self, items):
self.items = items
def __bool__(self):
return len(self.items) > 0
b = Bag([])
if not b:
print("Bag is empty") # Bag is empty__len__ for len()
__len__ makes len(obj) work. It also feeds __bool__ when no __bool__ is defined.
class Stack:
def __init__(self):
self.data = []
def push(self, v): self.data.append(v)
def __len__(self):
return len(self.data)
s = Stack()
s.push(1)
print(len(s)) # 1__eq__ for Equality
Define __eq__ to specify what makes two instances equal with ==.
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return self.x == other.x and self.y == other.y
print(Vector(1,2) == Vector(1,2)) # True__hash__ Pairing with __eq__
When you define __eq__, Python sets __hash__ to None, making the object unhashable. Define __hash__ too if you need the object in sets/dicts.
class Point:
def __init__(self, x, y): self.x, self.y = x, y
def __eq__(self, o): return (self.x, self.y) == (o.x, o.y)
def __hash__(self): return hash((self.x, self.y))
pts = {Point(1,2), Point(1,2)}
print(len(pts)) # 1__add__ and Arithmetic
Arithmetic operators map to dunder methods: __add__ for +, __sub__ for -, etc.
class Vector:
def __init__(self, x, y): self.x, self.y = x, y
def __add__(self, o): return Vector(self.x+o.x, self.y+o.y)
def __repr__(self): return f"Vector({self.x},{self.y})"
print(Vector(1,2) + Vector(3,4)) # Vector(4,6)__getitem__ for Indexing
__getitem__ lets your class support square-bracket indexing like obj[key].
class Matrix:
def __init__(self, data):
self.data = data
def __getitem__(self, idx):
return self.data[idx]
m = Matrix([[1,2],[3,4]])
print(m[0]) # [1, 2]
print(m[1][0]) # 3Quick Check
Which dunder method is called when you use print(obj)?
Recap
Magic methods give your classes Pythonic behaviour. __repr__ targets developers, __str__ targets users. Define __eq__, __hash__, and arithmetic dunders to make objects fully functional.
Frequently asked questions
Is the “Magic Methods: __str__ and __repr__” lesson free?
Yes — the full text of “Magic Methods: __str__ and __repr__” is free to read here on the web, and the Python Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO.
What will I learn in “Magic Methods: __str__ and __repr__”?
Implement dunder methods for readable object representations. You practise Python Academy 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 Python Academy?
No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Magic Methods: __str__ and __repr__” 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 Python Academy lesson?
Yes. Every Python Academy 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
- Classes and the __init__ Method
- Instance vs Class Attributes
- Instance Methods and self
- Magic Methods: __str__ and __repr__