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 tothisin 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 callprint(obj).__repr__(self): Official string representation of an object.__len__(self): Allows you to uselen(obj).__getitem__(self, key): Allows indexing likeobj[key].
π» Code example
python Standardclass 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 includeselfas the first argument in instance methods. - Custom Accessors: Creating Java-style getters/setters (
get_name,set_name) instead of using Python's@propertydecorator. - Private Access: Thinking
__privatemembers are truly inaccessible (they are just name-mangled).