Launch offer
Business website $150 USD Custom plugin $200 USD Ready in 5 days
Get a quote
Python

Magic / Dunder Methods in Python

Customize object behavior with special methods like __str__, __len__, and __add__.

Magic / Dunder Methods in Python — a practical guide to Python dunder methods with clear examples you can reuse in real projects.

Python Tutorial Series (51/95). Prefer one article? Read the complete Python tutorial.

Short description

Dunder methods hook into Python syntax and built-ins so your classes feel native.

__str__ and __len__

class Team:
    def __init__(self, members):
        self.members = members

    def __len__(self):
        return len(self.members)

    def __str__(self):
        return f'Team({len(self)})'

print(len(Team(['a', 'b'])), Team(['a', 'b']))

Leave a reply

Your email address will not be published. Required fields are marked *