Core Module
12 min forge

Python OOPs & Dunder Methods

Classes, Inheritance, and the magic of double underscores.

Python OOPs & Dunder Methods

πŸ“˜ What is it

Python is an object-oriented language. Classes and objects are at the heart of Python. One unique feature of Python OOP is Dunder (Double Under) Methods, also known as Magic Methods.

πŸ—οΈ Core Concepts

  • self: Refers to the current instance of the class (similar to this in Java/C++).
  • Inheritance: Subclasses inherit attributes and methods from parent classes.
  • Encapsulation: Python uses naming conventions (like _ or __) to signal private state.

πŸͺ„ Dunder Methods

Dunder methods allow you to implement operator overloading and customize built-in behaviors.

  • __init__(self): Constructor, called when an object is instantiated.
  • __str__(self): Controls what happens when you call print(obj).
  • __repr__(self): Official string representation of an object.
  • __len__(self): Allows you to use len(obj).
  • __getitem__(self, key): Allows indexing like obj[key].

πŸ’» Code example

python Standard
class Book: def __init__(self, title, author): self.title = title self.author = author def __str__(self): return f"'{self.title}' by {self.author}" def __len__(self): return len(self.title) my_book = Book("Fluent Python", "Luciano Ramalho") print(my_book) # Result: 'Fluent Python' by Luciano Ramalho print(len(my_book)) # Result: 13

❌ Common mistakes

  • Ignoring self: Forgetting to include self as the first argument in instance methods.
  • Custom Accessors: Creating Java-style getters/setters (get_name, set_name) instead of using Python's @property decorator.
  • Private Access: Thinking __private members are truly inaccessible (they are just name-mangled).