Skip to content
Unit 4 Syllabus Note· Programming in Python

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__() using self.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:

OperatorMagic MethodDescription
+__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 TypeDecoratorFirst ParameterCan Access
Instance MethodNoneselfInstance attributes & class attributes
Class Method@classmethodclsClass attributes, cannot access instance data directly (factory pattern)
Static Method@staticmethodNoneIsolated utility logic, access neither self nor cls

Python Exception Handling Architecture (try-except-else-finally)

Full Exception Handling Flow

  1. try: Encloses code that might trigger an exception.
  2. except ExceptionType as e: Catches and handles specific exceptions.
  3. else: Executes only if NO exception occurred in try.
  4. finally: Always executes (for cleanup like closing files or DB connections), regardless of errors.
  5. 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 @abstractmethod definitions, 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

Python
1"""
2MJPRU Examination Model Solution: Unit 4
3Object-Oriented Banking System with Custom Exceptions
4"""
5from abc import ABC, abstractmethod
6
7# Custom Exception
8class InsufficientFundsError(Exception):
9 """Raised when account balance is less than withdrawal amount."""
10 pass
11
12# Abstract Base Class
13class Account(ABC):
14 def __init__(self, acc_no, holder_name, initial_balance=0.0):
15 self._acc_no = acc_no # Protected
16 self.holder_name = holder_name # Public
17 self.__balance = initial_balance # Private (Name Mangled)
18
19 def get_balance(self):
20 return self.__balance
21
22 def deposit(self, amount):
23 if amount <= 0:
24 raise ValueError("Deposit amount must be positive!")
25 self.__balance += amount
26 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 -= amount
32 print(f"Withdrew Rs. {amount:.2f}. Remaining Balance: Rs. {self.__balance:.2f}")
33
34 @abstractmethod
35 def calculate_interest(self):
36 pass
37
38# Derived Class 1: Savings Account
39class SavingsAccount(Account):
40 INTEREST_RATE = 0.04 # 4% Annual interest
41
42 def calculate_interest(self):
43 interest = self.get_balance() * self.INTEREST_RATE
44 print(f"Annual Interest Calculated: Rs. {interest:.2f}")
45 return interest
46
47# Execution & Polymorphism
48savings = SavingsAccount("SB-10024", "Pooja Verma", 25000.0)
49savings.deposit(5000.0)
50savings.calculate_interest()
51try:
52 savings.withdraw(35000.0) # Triggers custom exception
53except 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

Python
1import math
2
3class Vector2D:
4 def __init__(self, x=0, y=0):
5 self.x = x
6 self.y = y
7
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.y
19
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 = 11
36print("Magnitude of v1:", v1.magnitude()) # 5.0

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

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

  1. Children precede parents.
  2. Order of base classes in declaration is preserved (B before C).
  3. 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.

Your reading progress
0%

100% left on this page — finishing it closes the gap for Classes, Objects, Inheritance & Advanced OOP.

Weak topic hint

Classes, Objects, Inheritance & Advanced OOP still counts as a weak topic until you finish this note and answer its questions.

Practise this unit
What Should You Do Next?

Test Your Understanding

Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.