Unit 6: Object-Oriented Programming in Python — Classes, Inheritance & Magic Methods
Comprehensive theory, executable code patterns, exam derivation traces, and supplementary printable PDF notes
Object-Oriented Programming (OOP) in Python is the foundational paradigm underpinning modern data engineering, machine learning pipelines (such as PyTorch models and Scikit-Learn transformers), and scalable backend architectures. In the SPPU Autonomous curriculum (ADES204), Unit 6 carries 14–18 marks in your end-term examination (ETE). This comprehensive chapter breaks down every core requirement: class creation, memory layout, constructors (`__init__`), encapsulation via name mangling, method resolution order (MRO) in multiple inheritance, operator overloading, and runtime polymorphism.
1. Classes, Objects, and the `self` Parameter
A class is a user-defined blueprint or prototype from which objects are created. An object is an instantiated instance of that blueprint residing in heap memory.
When defining methods inside a Python class, the first parameter must always be self. Unlike languages such as C++ or Java where this is an implicit keyword, Python makes object referencing explicit. When you invoke obj.method(arg), the Python interpreter translates it behind the scenes into Class.method(obj, arg).
class Student: # Class variable (shared across all instances) institution = "Zeal College of Engineering" def __init__(self, name, prn, sgpa): # Instance variables (unique to each object) self.name = name self.prn = prn self.sgpa = sgpa def display_profile(self): return f"Student: {self.name} | PRN: {self.prn} | SGPA: {self.sgpa:.2f}" # Instantiating objects: s1 = Student("Aarav Sharma", "PRN202401", 9.24) s2 = Student("Sneha Patil", "PRN202402", 9.58) print(s1.display_profile()) print(f"Institution: {Student.institution}")
2. Encapsulation & Access Specifiers (Public, Protected, Private)
Encapsulation binds data and the methods that manipulate that data together, preventing direct unauthorized external modification. Python does not use strict keywords like public or private; instead, it relies on naming conventions and name mangling:
- Public (e.g.,
self.name): Accessible from anywhere, inside or outside the class scope. - Protected (e.g.,
self._department): Denoted by a single leading underscore. Indicates by convention that it should only be accessed within the class and its subclasses. - Private (e.g.,
self.__account_balance): Denoted by double leading underscores. Triggers Python's name mangling mechanism, where the interpreter renames the attribute to_ClassName__attributeNameto prevent accidental overrides and direct external reads.
3. Inheritance & Method Resolution Order (MRO)
Inheritance allows a child class to inherit attributes and behaviors from one or more parent classes. Python supports five primary inheritance topologies:
- Single Inheritance: One parent class, one child class.
- Multilevel Inheritance: Class C inherits from Class B, which inherits from Class A.
- Multiple Inheritance: A child inherits directly from multiple independent parents (e.g.,
class C(A, B):). - Hierarchical Inheritance: Multiple child classes inherit from a single parent.
- Hybrid Inheritance: A combination of two or more of the above topologies.
When multiple inheritance forms diamond structures, Python resolves method calls using the C3 Superconcurrency Linearization (MRO) algorithm. You can inspect any class's resolution order by querying ClassName.mro() or ClassName.__mro__.
class DatasetLoader: def __init__(self, source): self.source = source print(f"[DatasetLoader] Initialized source: {self.source}") class ModelOptimizer: def __init__(self, learning_rate): self.lr = learning_rate print(f"[ModelOptimizer] Learning rate configured: {self.lr}") class MLPipeline(DatasetLoader, ModelOptimizer): def __init__(self, source, lr, pipeline_name): DatasetLoader.__init__(self, source) ModelOptimizer.__init__(self, lr) self.name = pipeline_name p = MLPipeline("data/students.csv", 0.001, "ETE-Classifier") print("MRO:", [c.__name__ for c in MLPipeline.mro()])
4. Polymorphism & Magic (Dunder) Methods
Polymorphism allows different classes to define methods with the exact same name, letting client code execute uniform operations without needing to know specific object types. In Python, this is enriched by Magic Methods (special double-underscore methods) that allow custom classes to integrate with built-in language operators:
⚙️ Essential Magic Methods for ETE Exam Papers
__init__(self, ...): Constructor method called when initializing a new object.__str__(self): Called byprint(obj)andstr(obj); returns human-readable representation.__repr__(self): Unambiguous machine-readable representation, typically for debugging.__add__(self, other): Overloads the+operator.__len__(self): Invoked by the built-inlen(obj)function.__eq__(self, other): Overloads the equality check==.
5. Typical Autonomous ETE Exam Questions & Full-Mark Answer Templates
Q1: Differentiate between Class Attributes and Instance Attributes with an illustrative code snippet. (6 Marks)
Answer Strategy: Define class attributes as variables bound to the class itself and shared among all instances, defined directly within the class body. Define instance attributes as variables tied to specific object instances, defined inside __init__ via self. Provide a complete 8-line working code example demonstrating how modifying a class variable reflects across all objects, whereas modifying an instance variable changes only that specific instance.
Q2: Explain Method Overriding vs Method Overloading in Python. (6 Marks)
Answer Strategy: Clarify that classical method overloading (multiple methods with the same name having different parameter signatures in the same class) is not natively supported in Python; the interpreter simply retains the last defined function. Note that overloading behavior is simulated using default arguments or *args / **kwargs. In contrast, method overriding occurs in an inheritance hierarchy where a child class provides a specialized implementation of a method already declared in its parent.
📥 Printable Chapter Reference (PDF Supplement)
Prefer a physical copy for offline revision or quick exam review? You can download our verified, printer-friendly PDF synthesis for Unit 6 below:
🔗 Related FY Semester 2 Study Units
- FY Semester 2 Library — Access full curriculum units across Python, Physics, Probability, and AI
- C++ OOP Deep Dive — Contrast Python's dynamic object model with C++'s compiled vtable architecture
- DSA Semester 3 Complete Roadmap — How to transition Python OOP concepts into data structure design