Unlocking Python's Magic: Mastering Dunder Methods

Ever wondered how Python knows what to do when you use + between two objects? Or how len() works on your custom class? The answer lies in magic methods (also called dunder methods). These are special methods wrapped in double underscores, and they're what make Python feel like magic. Here are a few that changed how I write code: __init__ — The constructor everyone knows. But it's just the beginning. __repr__ & __str__ — Control how your object looks when printed or logged. Debugging becomes 10x easier when your objects speak for themselves. __len__, __getitem__, __iter__ — Make your custom class behave like a built-in list or dictionary. Your teammates won't even know the difference. __enter__ & __exit__ — Power behind the with statement. Perfect for managing resources like files, DB connections, and locks. __eq__, __lt__, __gt__ — Define what "equal" or "greater than" means for your objects. Sorting a list of custom objects? No problem. __call__ — Make an instance callable like a function. This one unlocks some seriously clean design patterns. The real power of magic methods isn't just the syntax — it's that they let you write intuitive, Pythonic APIs that feel native to the language. When your custom class supports len(), iteration, and comparison naturally, your code becomes easier to read, test, and maintain. What's your favorite magic method? Drop it in the comments #Python #SoftwareEngineering #Programming #PythonTips #CleanCode #BackendDevelopment

  • text, chat or text message

That’s a good explanation. However, the actual constructor is __new__, while __init__ is an initializer. The __new__ method runs before the instance is created and is responsible for creating and returning the new object. The __init__ method runs after the instance has been created and is used to initialize its attributes.

Like
Reply

To view or add a comment, sign in

Explore content categories