Wednesday, June 18, 2025

What are "dunder" methods? Give an example.

All Questions From This Chapter

"Dunder" methods (short for "double underscore" methods) are special methods in Python that begin and end with double underscores (__), like __init__, __str__, and __len__. They’re also known as magic methods or special methods.

These methods are used to:

  • Customize the behavior of built-in operations

  • Enable operator overloading

  • Integrate your class with Python's core language features (like iteration, context managers, etc.)


Example:

python
class Book: def __init__(self, title): self.title = title def __str__(self): return f"Book: {self.title}" book = Book("Fluent Python") print(book) # Output: Book: Fluent Python
  • __init__: Initializes the object (like a constructor).

  • __str__: Defines what str(obj) or print(obj) returns.


🧠 Common Dunder Methods:

MethodPurpose
__init__Constructor (called on object creation)
__str__String representation (print(obj))
__repr__Debug representation (repr(obj))
__len__Length (len(obj))
__getitem__Indexing (obj[i])
__iter__Makes an object iterable
__eq__Equality (==)

Dunder methods let your objects behave like built-in types and integrate seamlessly with Python’s syntax and idioms.

Tags: Technology,Python,Interview Preparation,

No comments:

Post a Comment