๐๏ธ Python OOP โ Classes, Objects, and Inheritance
Object-Oriented Programming in Python uses classes to bundle data and behaviour together. Master classes, inheritance, and dunder methods.
Use @dataclass decorator (Python 3.7+) for simple data classes โ it auto-generates __init__, __repr__, and __eq__.
๐ป Code Example:
# 1. Basic class class PynfinityUser: platform = "pynfinity.com" # Class attribute (shared) def __init__(self, name, is_premium=False): self.name = name # Instance attribute self.is_premium = is_premium self._courses = [] # Protected attribute (by convention) def enroll(self, course): self._courses.append(course) print(f"{self.name} enrolled in {course}") def __repr__(self): return f"PynfinityUser(name={self.name!r}, premium={self.is_premium})" @property def course_count(self): return len(self._courses) # 2. Inheritance class PremiumUser(PynfinityUser): def __init__(self, name): super().__init__(name, is_premium=True) self.badge = "โญ Premium" def get_ai_course(self): return f"{self.name} accessing Infinite AI Course" # Usage user = PynfinityUser("santoshtvk") user.enroll("Infinite Python") print(user) # PynfinityUser(name='santoshtvk', premium=False) print(user.course_count) # 1 premium = PremiumUser("dhruv") print(premium.get_ai_course()) print(isinstance(premium, PynfinityUser)) # True โ inheritance
| Concept | Key Takeaway |
|---|---|
| __init__ | Constructor โ called on object creation |
| __repr__ | String representation for debugging |
| __str__ | User-facing string (used by print()) |
| @property | Define computed attributes with getter logic |
| super() | Call methods from parent class |
| isinstance(obj, Class) | Safe type checking with inheritance awareness |
Keep exploring and happy coding! ๐