Programming in Python
Comprehensive exam revision notes for BCA-202N Unit 4 (Classes, Objects, Inheritance & Advanced OOP). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Programming in Python
Classes, Objects, Inheritance & Advanced OOP
Core Definitions & Key Concepts
What is the purpose of the __init__() method in Python
__init__() is the class constructor in Python. It is automatically called when a new instance of a class is instantiated to initialize instance attributes.
What does the self parameter represent in Python methods
self represents the instance of the class itself. It explicitly passes the object's reference so methods can access and modify the object's attributes and other methods.
Class variables and instance variables
- Class Variables: Shared across all instances of a class, defined inside the class body but outside methods.
- Instance Variables: Unique to each individual object instance, typically initialized inside
__init__()usingself.var.
How does Python implement data encapsulation and private members
Python uses naming conventions rather than language keywords:
- Single underscore
_var: Protected (convention only). - Double underscore
__var: Private (enforces Name Mangling to_ClassName__var).
What is Method Overriding in Python
Method overriding occurs when a child subclass provides a specific implementation of a method that is already defined in its parent superclass, replacing parent behavior.
What does super() do in Python OOP
super() returns a proxy object delegating method calls to a parent or sibling class in the inheritance chain, following the Method Resolution Order (MRO).
Method Resolution Order (MRO) and C3 Linearization
MRO is the deterministic order in which Python searches base classes for attributes and methods in multiple inheritance, computed using the C3 Linearization Algorithm (viewed via Class.__mro__).
What are magic (dunder) methods in Python? Give two examples
Magic methods have double leading and trailing underscores: e.g., __str__() (user-friendly string representation) and __len__() (returns length for len(obj)).
Conceptual & Architectural Analysis
Operator Overloading in Python with Common Dunder Methods
Operator Overloading via Magic Methods
Python permits operators (+, -, *, ==) to be customized for user-defined classes by implementing special methods:
| Operator | Magic Method | Description |
|---|---|---|
+ | __add__(self, other) | Addition |
- | __sub__(self, other) | Subtraction |
* | __mul__(self, other) | Multiplication |
== | __eq__(self, other) | Equality comparison |
< | __lt__(self, other) | Less than |
str(obj) | __str__(self) | Readable string representation |
repr(obj) | __repr__(self) | Unambiguous developer representation |
@staticmethod, @classmethod, and Regular Instance Methods
| Method Type | Decorator | First Parameter | Can Access |
|---|---|---|---|
| Instance Method | None | self | Instance attributes & class attributes |
| Class Method | @classmethod | cls | Class attributes, cannot access instance data directly (factory pattern) |
| Static Method | @staticmethod | None | Isolated utility logic, access neither self nor cls |
Python Exception Handling Architecture (try-except-else-finally)
Full Exception Handling Flow
try: Encloses code that might trigger an exception.except ExceptionType as e: Catches and handles specific exceptions.else: Executes only if NO exception occurred intry.finally: Always executes (for cleanup like closing files or DB connections), regardless of errors.raise: Manually throws an exception.
Abstract Base Classes (ABCs) in Python
Python supports abstract classes via the built-in abc module (ABC and @abstractmethod):
- An abstract class cannot be directly instantiated.
- Subclasses MUST implement all
@abstractmethoddefinitions, enforcing consistent API contracts across polymorphic classes.
In-Depth Analysis & Implementation
Develop a Complete Banking System Class Hierarchy Demonstrating Inheritance, Encapsulation, Polymorphism, and Custom Exceptions
1"""2MJPRU Examination Model Solution: Unit 43Object-Oriented Banking System with Custom Exceptions4"""5from abc import ABC, abstractmethod6
7# Custom Exception8class InsufficientFundsError(Exception):9 """Raised when account balance is less than withdrawal amount."""10 pass11
12# Abstract Base Class13class Account(ABC):14 def __init__(self, acc_no, holder_name, initial_balance=0.0):15 self._acc_no = acc_no # Protected16 self.holder_name = holder_name # Public17 self.__balance = initial_balance # Private (Name Mangled)18 19 def get_balance(self):20 return self.__balance21 22 def deposit(self, amount):23 if amount <= 0:24 raise ValueError("Deposit amount must be positive!")25 self.__balance += amount26 print(f"Deposited Rs. {amount:.2f}. New Balance: Rs. {self.__balance:.2f}")27 28 def withdraw(self, amount):29 if amount > self.__balance:30 raise InsufficientFundsError(f"Cannot withdraw Rs. {amount}. Available: Rs. {self.__balance}")31 self.__balance -= amount32 print(f"Withdrew Rs. {amount:.2f}. Remaining Balance: Rs. {self.__balance:.2f}")33 34 @abstractmethod35 def calculate_interest(self):36 pass37
38# Derived Class 1: Savings Account39class SavingsAccount(Account):40 INTEREST_RATE = 0.04 # 4% Annual interest41 42 def calculate_interest(self):43 interest = self.get_balance() * self.INTEREST_RATE44 print(f"Annual Interest Calculated: Rs. {interest:.2f}")45 return interest46
47# Execution & Polymorphism48savings = SavingsAccount("SB-10024", "Pooja Verma", 25000.0)49savings.deposit(5000.0)50savings.calculate_interest()51try:52 savings.withdraw(35000.0) # Triggers custom exception53except InsufficientFundsError as err:54 print("Transaction Error Caught:", err)Demonstrate Operator Overloading by Implementing a 2D Vector Class with Addition, Subtraction, Dot Product, and String Representation
1import math2
3class Vector2D:4 def __init__(self, x=0, y=0):5 self.x = x6 self.y = y7 8 def __add__(self, other):9 """Overloads + operator: v1 + v2"""10 return Vector2D(self.x + other.x, self.y + other.y)11 12 def __sub__(self, other):13 """Overloads - operator: v1 - v2"""14 return Vector2D(self.x - other.x, self.y - other.y)15 16 def __mul__(self, other):17 """Overloads * operator for Dot Product: v1 * v2"""18 return self.x * other.x + self.y * other.y19 20 def magnitude(self):21 return math.sqrt(self.x**2 + self.y**2)22 23 def __str__(self):24 return f"Vector2D({self.x}, {self.y})"25 26 def __repr__(self):27 return f"Vector2D(x={self.x}, y={self.y})"28
29v1 = Vector2D(3, 4)30v2 = Vector2D(1, 2)31print("v1:", v1)32print("v2:", v2)33print("v1 + v2:", v1 + v2) # Vector2D(4, 6)34print("v1 - v2:", v1 - v2) # Vector2D(2, 2)35print("Dot Product:", v1 * v2) # 3*1 + 4*2 = 1136print("Magnitude of v1:", v1.magnitude()) # 5.0Multiple Inheritance and the Diamond Problem in Python with C3 MRO Linearization
The Diamond Problem and C3 MRO in Python
When class D inherits from B and C, and both inherit from A, a diamond hierarchy is formed.
1class A:2 def execute(self):3 print("A.execute()")4
5class B(A):6 def execute(self):7 print("B.execute()")8 super().execute()9
10class C(A):11 def execute(self):12 print("C.execute()")13 super().execute()14
15class D(B, C):16 def execute(self):17 print("D.execute()")18 super().execute()19
20d = D()21d.execute()22print("\nMRO of D:", [cls.__name__ for cls in D.__mro__])23# MRO: ['D', 'B', 'C', 'A', 'object']Why Python solves this cleanly: C3 Linearization ensures:
- Children precede parents.
- Order of base classes in declaration is preserved (
BbeforeC). - Every class is evaluated exactly once.
Important Exam Points & Quick Revision
Be ready to write full class hierarchies with super(), explain Name Mangling, and solve the Diamond Problem with MRO.
100% left on this page — finishing it closes the gap for Classes, Objects, Inheritance & Advanced OOP.
Classes, Objects, Inheritance & Advanced OOP still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.