Unlock Python’s Magic: Master Dunder Methods for Cleaner, Powerful Code
Learn how Python’s special “dunder” methods like __str__, __add__, __eq__, __iter__, and others let you customize object representation, arithmetic, comparison, and iteration, turning your classes into intuitive, built‑in‑type equivalents with clear examples and practical code snippets.
Python’s dunder (double‑underscore) methods are built‑in functions that let you control how objects behave, making your code more concise, intuitive, and powerful.
What Are Dunder Methods?
Dunder methods such as __str__, __repr__, __add__, and others let you customize object behavior to match your specific needs.
Want your object to print like a regular string? Implement __str__.
Need to compare two instances? Implement __eq__.
Want your object to support the + operator? Implement __add__.
Ugly Print Output ( __str__ & __repr__ )
Without custom methods, printing an instance shows a memory address:
Define a simple class:
class Book:
def __init__(self, title, author):
self.title = title
self.author = authorPrinting an instance now yields the default representation:
b = Book("1984", "George Orwell")
print(b)Implement __str__ and __repr__ to improve output:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f'"{self.title}" by {self.author}'
def __repr__(self):
return f'Book(title="{self.title}", author="{self.author}")'Now printing the object gives a readable string:
b = Book("1984", "George Orwell")
print(b) "1984" by George OrwellMake Objects Behave Like Numbers ( __add__ , __sub__ )
Define a Wallet class that can be added:
wallet1 = Wallet( 50 )
wallet2 = Wallet( 30 )
total = wallet1 + wallet2 # should add balancesImplement __add__:
class Wallet:
def __init__(self, balance):
self.balance = balance
def __add__(self, other):
if isinstance(other, Wallet):
return Wallet(self.balance + other.balance)
return NotImplementedUsing it:
w1 = Wallet(50)
w2 = Wallet(30)
w3 = w1 + w2
print(w3.balance) # 80The same approach works for subtraction ( __sub__), multiplication ( __mul__), and comparisons ( __lt__, __gt__).
Compare Objects ( __eq__ , __gt__ , __lt__ )
By default, Python compares object identities, not their contents. Implement __eq__ to compare balances:
class Wallet:
def __init__(self, balance):
self.balance = balance
def __eq__(self, other):
if isinstance(other, Wallet):
return self.balance == other.balance
return FalseNow:
w1 = Wallet(50)
w2 = Wallet(50)
print(w1 == w2) # TrueMake Objects Iterable ( __iter__ , __next__ )
To iterate over a custom container, implement __iter__ and __next__:
class TransactionHistory:
def __init__(self, transactions):
self.transactions = transactions
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index >= len(self.transactions):
raise StopIteration
transaction = self.transactions[self.index]
self.index += 1
return transactionUsing it:
history = TransactionHistory(["Deposit $100", "Withdraw $50", "Deposit $200"])
for transaction in history:
print(transaction)Deposit $100
Withdraw $50
Deposit $200Final Thoughts
Dunder methods are not just a curiosity; they let your classes feel like built‑in Python types. Without __str__, objects print as garbage; without __eq__, Python cannot determine equality; without __iter__, you cannot loop over them. Mastering these methods makes your code more powerful and expressive.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Services Circle
Delivering cutting-edge internet insights and practical learning resources. We're a passionate and principled IT media platform.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
