Special (dunder) methods
Methods with double underscores on both sides, like __init__, are special methods (nicknamed "dunder" methods, for double underscore). Python calls them for you when you use built-in syntax, so your objects can behave like built-in types.
__str__ and __repr__: how an object prints
Without them, printing an object isn't helpful:
Python
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
print(Point(3, 4))Define __str__ for a readable display and __repr__ for an unambiguous, developer-facing one:
Python
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __str__(self):
return f"({self.x}, {self.y})"
def __repr__(self):
return f"Point({self.x}, {self.y})"
p = Point(3, 4)
print(p) # uses __str__
print(repr(p)) # uses __repr__
print([p, p]) # lists show their items with __repr____eq__: what == means
By default, == between two objects checks whether they're the same object. Define __eq__ to compare their values:
Python
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
print(Point(1, 2) == Point(1, 2))
print(Point(1, 2) == Point(2, 1))Arithmetic: __add__ and friends
Python
class Money:
def __init__(self, amount, currency="INR"):
self.amount, self.currency = amount, currency
def __add__(self, other):
if self.currency != other.currency:
raise ValueError("Currencies differ")
return Money(self.amount + other.amount, self.currency)
def __mul__(self, factor):
return Money(self.amount * factor, self.currency)
def __str__(self):
return f"{self.currency} {self.amount:,.2f}"
price = Money(250)
print(price + Money(99.5))
print(price * 3)Length, comparison and sorting
Python
class Playlist:
def __init__(self, name, songs):
self.name, self.songs = name, songs
def __len__(self):
return len(self.songs)
def __lt__(self, other): # makes < work, which sorted() uses
return len(self) < len(other)
def __repr__(self):
return f"{self.name}({len(self)})"
lists = [Playlist("Chill", ["a", "b", "c"]), Playlist("Focus", ["d"]), Playlist("Party", ["e", "f"])]
print(len(lists[0]))
print(sorted(lists))Common special methods
| Method | Called by |
|---|---|
__init__ | Thing(...) |
__str__ / __repr__ | print(x), str(x) / repr(x) |
__len__ | len(x) |
__eq__, __lt__, __le__... | ==, <, <= ... |
__add__, __sub__, __mul__ | +, -, * |
__contains__ | item in x |
__getitem__ | x[key] |
__iter__ | for item in x |
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.