Special (Dunder) Methods
Methods with double underscores let your objects work with Python itself. __str__ is what print shows, __repr__ is the developer view, __len__ powers len(), __eq__ powers == and __add__ powers +. This is called operator overloading.
Example
class Money:
def __init__(self, amount):
self.amount = amount
def __str__(self):
return f"NGN {self.amount:,}"
def __repr__(self):
return f"Money({self.amount})"
def __add__(self, other):
return Money(self.amount + other.amount)
def __eq__(self, other):
return self.amount == other.amount
a, b = Money(1500), Money(2500)
print(a + b)
print(repr(a))
print(a == Money(1500))Result
NGN 4,000 Money(1500) True
Exercise
Which method gives the text shown by print?
def (self): return "text"
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.