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
- Classes and the __init__ Method
- Instance vs Class Attributes
- Instance Methods and self
- Magic Methods: __str__ and __repr__