Python OOP Deep Dive: Classes, Encapsulation, Magic Methods & MRO
Master Object-Oriented Programming in Python: classes, __init__, encapsulation with property decorators, multiple inheritance, and Method Resolution Order (MRO).
class SoftwareCourse:
def __init__(self, name: str, duration_weeks: int):
self._name = name # Protected attribute by convention
self._duration_weeks = duration_weeks
@property
def duration_weeks(self) -> int:
return self._duration_weeks
@duration_weeks.setter
def duration_weeks(self, weeks: int):
if weeks <= 0:
raise ValueError("Duration must be a positive integer")
self._duration_weeks = weeks
def __str__(self) -> str:
return f"{self._name} ({self._duration_weeks} Weeks)"
course = SoftwareCourse("Python Full Stack", 14)
print(course)
course.duration_weeks = 16
print("Updated duration:", course.duration_weeks)
1. Classes & Instances in Python
Python treats classes as first-class objects. The __init__ constructor initializes attributes on the newly created instance referenced by self.
2. Encapsulation & Property Decorators
Python does not enforce private variables at the bytecode level. Instead, the community adheres to naming conventions: single underscore (_var) denotes protected fields, while double underscore (__var) triggers name mangling to prevent subclass collisions. Use @property to implement getters and setters cleanly.
- Dunder methods like __str__ and __repr__ enable custom string representations and operator overloading.
- Python supports multiple inheritance resolved through the C3 Linearization algorithm (MRO).
- Prefer dataclasses for simple structured data models.
Frequently Asked Questions
What is the purpose of self in Python methods?
Gain deep mastery over these concepts with direct instructor guidance, code reviews, and mock interviews at C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad.
Explore Related Course Call 7503962162