Skip to primary content
Python Technical Tutorial

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).

Python
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.

Key Engineering Takeaways
  • 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?
self represents the specific instance of the class upon which a method is called, giving access to instance attributes.
Master This in Our Ghaziabad Coding Labs

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
Physical Training Center

Visit Our Ghaziabad Training Center

Join classroom batches, attend interactive lab sessions, code with mentors, and take advantage of our high-speed dev workstations.

Campus Address:
C-60 R.K Tower, 3rd Floor, RDC, Ghaziabad, Ghaziabad, Uttar Pradesh
Direct Counseling Helpline:
Call 7503962162
Get Google Maps Directions Call Now: 7503962162 Explore Ghaziabad Training Hub
Call 7503962162 Get Course Details