11. Object-Oriented Programming (OOP)
Master essential Python OOP: `Classes`, `Objects`, `self`, `__init__`, `Instance vs Class Variables`, `@classmethod`, `@staticmethod`, `Inheritance`, `super()`, the `4 Pillars of OOP`, and essential `Dunder Methods` (`__str__`, `__repr__`, `__len__`, `__eq__`, `__lt__`, `__iter__`, `__next__`).
🎓 Junior Python Curriculum — Select Module
11. Python Object-Oriented Programming (OOP) Essentials
1️⃣ Classes, Objects, Attributes, `self` & `__init__`
A Class is a blueprint for creating objects. An Object is a concrete instance of that class. The __init__ method initializes object attributes when instantiated, and self represents the instance invoking the method.
def __init__(self, username):
self.username = username # Instance variable
2️⃣ Instance vs. Class Variables & Method Types
Instance variables are unique to each object. Class variables are shared across all instances.
- Instance Method: Takes
selfas first parameter; operates on instance data. - Class Method (`@classmethod`): Takes
clsas first parameter; operates on class state. - Static Method (`@staticmethod`): Takes no mandatory self/cls; utility function bound to namespace.
3️⃣ Inheritance, Multiple Inheritance & `super()`
Child classes inherit attributes and methods from parent classes. Use super().__init__() to invoke parent constructors safely. Python also supports Multiple Inheritance (`class Child(ParentA, ParentB)`).
def __init__(self, username, role="Admin"):
super().__init__(username)
self.role = role
4️⃣ Composition vs. Inheritance
Inheritance ("is-a"): A Developer is an Employee.
Composition ("has-a"): A Car has an Engine object as an attribute. Composition increases code flexibility and reduces tight coupling.
5️⃣ Special / Dunder Methods Reference Matrix
| Dunder Method | Triggered By | Description & Use Case |
|---|---|---|
| __init__(self, ...) | User("Dilshad") |
Constructor method initializing instance attributes. |
| __str__(self) | str(obj) or print(obj) |
User-friendly string representation. |
| __repr__(self) | repr(obj) or REPL terminal |
Developer unambiguous string representation for debugging. |
| __len__(self) | len(obj) |
Returns collection or dataset size integer. |
| __eq__(self, other) | obj1 == obj2 |
Custom equality comparison logic. |
| __lt__(self, other) | obj1 < obj2 |
Less-than comparison enabling sorting with sorted(). |
| __iter__ / __next__ | for item in obj: |
Makes custom class objects iterable sequences. |