Fundamentals 6 min read

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.

Data STUDIO
Data STUDIO
Data STUDIO
How Python Dunder Methods Make Your Code Cleaner and More Powerful

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 Orwell

Example: 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 NotImplemented

Now 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 False

Two 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 transaction

Iterating 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythoniterationoperator overloadingmagic methodsdunder methodscustom classes
Data STUDIO
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.