How Python Dunder Methods Make Your Code Cleaner and More Powerful
This article explains Python's dunder (double‑underscore) magic methods, showing how overriding __str__, __repr__, __add__, __eq__, __iter__, and others lets custom classes behave like built‑in types, with concrete examples such as Book, Wallet, and TransactionHistory.
Dunder methods explained
Dunder (double‑underscore) methods are built‑in Python functions that let you control an object's behavior, making your code more concise, intuitive, and powerful.
Common dunder methods
__str__: define how an object is printed as a human‑readable string. __repr__: define the representation shown in the debugger. __add__: enable the + operator for custom objects. __eq__: customize equality comparison. __lt__, __gt__: customize ordering. __iter__ and __next__: make an object iterable.
Example: pretty printing with __str__ and __repr__
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}")'Printing a Book instance now yields a readable string instead of a memory address:
b = Book("1984", "George Orwell")
print(b)
# Output: "1984" by George OrwellExample: operator overloading with __add__
Define a Wallet class that can be added to another wallet:
class Wallet:
def __init__(self, balance):
self.balance = balance
def __add__(self, other):
if isinstance(other, Wallet):
return Wallet(self.balance + other.balance)
return NotImplementedNow w1 + w2 returns a new Wallet with the combined balance (e.g., 80).
Example: custom equality with __eq__
class Wallet:
def __init__(self, balance):
self.balance = balance
def __eq__(self, other):
if isinstance(other, Wallet):
return self.balance == other.balance
return FalseTwo wallets with the same balance compare as True.
Example: making an object iterable with __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 transactionIterating over TransactionHistory now yields each transaction like a list.
Conclusion
Dunder methods let custom classes feel like built‑in Python types. Without __str__ objects print as unreadable memory addresses, without __eq__ Python cannot determine logical equality, and without __iter__ they cannot be looped over. Using these magic methods makes code cleaner, more expressive, and easier to maintain.
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.
Data STUDIO
Click to receive the "Python Study Handbook"; reply "benefit" in the chat to get it. Data STUDIO focuses on original data science articles, centered on Python, covering machine learning, data analysis, visualization, MySQL and other practical knowledge and project case studies.
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.
