0% found this document useful (0 votes)
0 views15 pages

Python Unit 4

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism, along with examples in Python. It explains the four pillars of OOP and contrasts it with procedural programming, emphasizing the benefits of OOP such as code reusability and easier program management. Additionally, it includes practical code examples demonstrating the implementation of these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views15 pages

Python Unit 4

The document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism, along with examples in Python. It explains the four pillars of OOP and contrasts it with procedural programming, emphasizing the benefits of OOP such as code reusability and easier program management. Additionally, it includes practical code examples demonstrating the implementation of these concepts.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming BCA Semester IV

UNIT Object-Oriented Programming (OOP)

4 Course 24MJBCA4L1 | Semester IV |


BCA
Classes · Objects · Encapsulation · Inheritance
12 Hours
· Polymorphism · Modules · Packages

2-MARK QUESTIONS 5-MARK QUESTIONS 10-MARK QUESTIONS


What is OOP? / What is Explain encapsulation / Explain all OOP concepts
inheritance? polymorphism / modules with full programs / class
with programs hierarchy programs

4.1 Introduction to OOP

📌 Definition — Object-Oriented Programming (OOP)

A programming paradigm where a program is designed as a collection of OBJECTS that


interact with each other. Each object combines DATA (attributes) and BEHAVIOUR
(methods) in a single unit called a class.

The 4 Pillars of OOP:


1. Encapsulation — Hiding internal data; controlled access through methods
2. Inheritance — Child class acquires properties of parent class
3. Polymorphism — Same method name, different behaviour in different classes
4. Abstraction — Hiding complexity; exposing only essential features

🌍 Real-Life Analogy

Think of a real-world BANK. The bank has objects: Customer, Account, Loan,
Transaction. Each Account object has DATA: account number, balance, interest rate. Each
Account has BEHAVIOUR: deposit(), withdraw(), get_balance(). Encapsulation: balance
is private — you can't directly change it. Inheritance: SavingsAccount and
CurrentAccount both inherit from Account. Polymorphism: calculate_interest() works
differently for each type.

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 1 of 15
Python Programming BCA Semester IV
Procedural Programming Object-Oriented Programming
Program = sequence of functions Program = collection of objects
Data and functions are SEPARATE Data and functions BUNDLED in a class
Data can be modified from anywhere Data is protected inside classes
Hard to manage large programs Easy — divide into well-defined classes
Code reuse via copy-paste Code reuse via Inheritance
Examples: C, Pascal Examples: Python, Java, C++, Ruby

4.2 Classes and Objects

📌 Definition — Class

A BLUEPRINT or TEMPLATE for creating objects.


Defines the attributes (data) and methods (behaviour) that all objects will have.
Defined using the 'class' keyword.

📌 Definition — Object

A specific INSTANCE of a class — the actual thing built from the blueprint.
A class can have many objects; each has its own data but shares the same methods.

Analogy: Class = Architecture blueprint of a house.


Object = The actual house built from that blueprint.
Many houses (objects) can be built from the same blueprint (class).

📋 Syntax

class ClassName:
class_var = value # Shared by ALL objects

def __init__(self, p1, p2): # Constructor — runs when object is created


self.attr1 = p1 # Instance variable — unique to each object
self.attr2 = p2

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 2 of 15
Python Programming BCA Semester IV

def method(self): # Instance method


return something

obj = ClassName(arg1, arg2) # Create an object

▶ Classes and Objects — Student Class


class Student:
college = 'BCA College' # Class variable — shared by all
total = 0 # Count of all students

def __init__(self, name, usn, cgpa):


[Link] = name # Instance variable — unique
[Link] = usn
[Link] = cgpa
[Link] = []
[Link] += 1 # Increment class counter

def add_marks(self, *marks):


[Link](marks)

def average(self):
return sum([Link])/len([Link]) if [Link] else 0

def grade(self):
avg = [Link]()
if avg >= 90: return 'O'
elif avg >= 80: return 'A+'
elif avg >= 70: return 'A'
elif avg >= 60: return 'B+'
elif avg >= 40: return 'C'
else: return 'F'

def is_topper(self): return [Link] >= 9.0

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 3 of 15
Python Programming BCA Semester IV
def display(self):
print(f'Name : {[Link]}')
print(f'USN : {[Link]}')
print(f'College: {[Link]}')
print(f'CGPA : {[Link]}')
print(f'Avg : {[Link]():.1f} Grade: {[Link]()}')

def __str__(self):
return f'Student({[Link]}, CGPA={[Link]})'

# Create objects
s1 = Student('Ananya', 'BCA001', 9.1)
s2 = Student('Rahul', 'BCA002', 8.5)

s1.add_marks(85, 90, 78, 92, 88)


s2.add_marks(72, 68, 75, 80)

print(s1) # Uses __str__


[Link]()
print(f'Total students: {[Link]}')

► Output:
Student(Ananya, CGPA=9.1)
Name : Ananya
USN : BCA001
College: BCA College
CGPA : 9.1
Avg : 86.6 Grade: A+
Total students: 2

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 4 of 15
Python Programming BCA Semester IV
4.3 Encapsulation

📌 Definition — Encapsulation

Hiding internal data of a class from direct outside access.


Providing CONTROLLED access through public methods (getters/setters).

Access levels in Python (by naming convention):


public_attr → Accessible from anywhere (default)
_protected_attr → Convention: should not access from outside (single underscore)
__private_attr → Name-mangled to _ClassName__attr (double underscore)
Python makes it hard (not impossible) to access from outside.

Getter: Method that RETURNS the value of a private attribute


Setter: Method that VALIDATES and SETS a private attribute's value

🌍 Real-Life Analogy

An ATM machine — your money (data) is sealed inside the machine (class). You interact
ONLY through the machine's interface: deposit, withdraw, check balance. You can't reach
inside the machine directly — that's encapsulation.

▶ Encapsulation — Bank Account


class BankAccount:
bank_name = 'Python National Bank'
interest_rate = 4.5

def __init__(self, holder, deposit=0):


[Link] = holder # Public
self.__balance = deposit # PRIVATE
self.__history = [] # PRIVATE

# Getter — safely read private data


def get_balance(self): return self.__balance
def get_history(self): return list(self.__history)

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 5 of 15
Python Programming BCA Semester IV

# Deposit method
def deposit(self, amount):
if amount <= 0:
raise ValueError('Deposit must be positive!')
self.__balance += amount
self.__history.append(f'+ Rs.{amount:,.0f}')
print(f'Deposited Rs.{amount:,}. Balance: Rs.{self.__balance:,}')

# Withdraw method
def withdraw(self, amount):
if amount <= 0:
raise ValueError('Amount must be positive!')
if amount > self.__balance:
raise ValueError(f'Insufficient! Available: Rs.{self.__balance}')
self.__balance -= amount
self.__history.append(f'- Rs.{amount:,.0f}')
print(f'Withdrew Rs.{amount:,}. Balance: Rs.{self.__balance:,}')

def __str__(self):
return f'Account[{[Link]}] Balance: Rs.{self.__balance:,}'

acc = BankAccount('Ananya', 10000)


print(acc)
[Link](5000)
[Link](3000)
print('Current balance:', acc.get_balance())
print('History:', acc.get_history())
# print(acc.__balance) # AttributeError — private!

► Output:
Account[Ananya] Balance: Rs.10,000
Deposited Rs.5,000. Balance: Rs.15,000
Withdrew Rs.3,000. Balance: Rs.12,000
Current balance: 12000
History: ['+ Rs.5,000', '- Rs.3,000']

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 6 of 15
Python Programming BCA Semester IV
4.4 Inheritance

📌 Definition — Inheritance

A mechanism where a new class (child/derived class) acquires attributes and methods
from an existing class (parent/base class).
The child class can also ADD new attributes/methods and OVERRIDE inherited ones.

Benefits: Code Reusability, Extensibility, Hierarchy

Types of Inheritance:
1. Single — One child inherits from one parent
2. Multiple — One child inherits from multiple parents
3. Multilevel — A → B → C (chain of inheritance)
4. Hierarchical— Multiple children from one parent
5. Hybrid — Combination of above types

super() — Calls the parent class's __init__ or methods from inside the child.

🌍 Real-Life Analogy

Children inherit traits from parents — eye color, surname. But children also have their
own unique traits. SavingsAccount inherits all Account properties (deposit, withdraw)
but adds its own feature (interest calculation at a specific rate).

▶ Inheritance — Animal Hierarchy


# ── Parent class
──────────────────────────────────────────────
class Animal:
def __init__(self, name, sound):
[Link] = name
[Link] = sound

def breathe(self):
print(f'{[Link]} is breathing.')

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 7 of 15
Python Programming BCA Semester IV

def speak(self):
print(f'{[Link]} says: {[Link]}!')

def __str__(self):
return f'{type(self).__name__}({[Link]})'

# ── Single Inheritance
─────────────────────────────────────────
class Dog(Animal): # Dog IS-A Animal
def __init__(self, name, breed):
super().__init__(name, 'Woof') # Call parent __init__
[Link] = breed

def fetch(self):
print(f'{[Link]} fetches the ball!')

class Cat(Animal):
def __init__(self, name, indoor):
super().__init__(name, 'Meow')
[Link] = indoor

def purr(self):
print(f'{[Link]} is purring...')

# ── Multiple Inheritance ───────────────────────────────────────


class Flyable:
def fly(self): print(f'{[Link]} is flying!')

class Swimmable:
def swim(self): print(f'{[Link]} is swimming!')

class Duck(Animal, Flyable, Swimmable):


def __init__(self, name):
super().__init__(name, 'Quack')

# ── Multilevel Inheritance ─────────────────────────────────────


From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 8 of 15
Python Programming BCA Semester IV
class GuideDog(Dog): # GuideDog → Dog → Animal
def guide(self):
print(f'{[Link]} guides the visually impaired.')

# Testing
dog = Dog('Bruno', 'Labrador')
cat = Cat('Whiskers', True)
duck = Duck('Donald')
guide = GuideDog('Max', 'Golden Retriever')

[Link]() # Inherited from Animal


[Link]() # Inherited from Animal
[Link]() # Dog's own method
[Link]() # From Flyable
[Link]() # From Swimmable
[Link]() # GuideDog's own method

# isinstance and issubclass


print(isinstance(dog, Animal)) # True
print(isinstance(dog, Dog)) # True
print(issubclass(Dog, Animal)) # True
print(issubclass(GuideDog, Dog)) # True

4.5 Polymorphism

📌 Definition — Polymorphism

Means 'many forms'. The same method name behaves DIFFERENTLY based on the object
that calls it.

Achieved through:
1. Method Overriding — Child class redefines a parent's method
2. Duck Typing — Python cares about method existence, not type
3. Operator Overloading — Same operator works differently for different types

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 9 of 15
Python Programming BCA Semester IV
Real example: '+' operator:
5 + 3 = 8 (addition)
'Hi' + '!' = 'Hi!' (concatenation)
Same symbol, different behaviour — that is polymorphism.

🌍 Real-Life Analogy

The word 'run' has different meanings: A person runs. A program runs. A nose runs.
Same word (method name), different action (implementation) based on context (object
type).

▶ Polymorphism — Shape Hierarchy


import math

class Shape:
def area(self): return 0 # Base implementation
def perimeter(self): return 0
def describe(self):
print(f'{type(self).__name__}: area={[Link]():.2f}, perim={[Link]():.2f}')

class Circle(Shape):
def __init__(self, r): self.r = r
def area(self): return [Link] * self.r ** 2
def perimeter(self): return 2 * [Link] * self.r

class Rectangle(Shape):
def __init__(self, w, h): self.w=w; self.h=h
def area(self): return self.w * self.h
def perimeter(self): return 2 * (self.w + self.h)

class Triangle(Shape):
def __init__(self, a, b, c): self.a=a; self.b=b; self.c=c
def area(self):
s = (self.a+self.b+self.c)/2
return [Link](s*(s-self.a)*(s-self.b)*(s-self.c))

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 10 of 15
Python Programming BCA Semester IV
def perimeter(self): return self.a+self.b+self.c

shapes = [Circle(7), Rectangle(8,5), Triangle(3,4,5)]

# Polymorphism in action — same loop, different results


for s in shapes:
[Link]() # calls different area() for each

total = sum([Link]() for s in shapes)


print(f'Total area: {total:.2f}')

► Output:
Circle : area=153.94, perim=43.98
Rectangle: area=40.00, perim=26.00
Triangle : area=6.00, perim=12.00
Total area: 199.94

▶ Operator Overloading
# Operator Overloading using special/dunder methods
class Vector:
def __init__(self, x, y): self.x=x; self.y=y
def __add__(self, o): return Vector(self.x+o.x, self.y+o.y)
def __sub__(self, o): return Vector(self.x-o.x, self.y-o.y)
def __mul__(self, n): return Vector(self.x*n, self.y*n)
def __eq__(self, o): return self.x==o.x and self.y==o.y
def __str__(self): return f'Vector({self.x}, {self.y})'
def magnitude(self): return (self.x**2 + self.y**2)**0.5

v1 = Vector(2, 3); v2 = Vector(4, 1)


print(v1 + v2) # Vector(6, 4)
print(v1 - v2) # Vector(-2, 2)
print(v1 * 3) # Vector(6, 9)
print(v1 == v2) # False
print(f'|v1| = {[Link]():.2f}') # 3.61

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 11 of 15
Python Programming BCA Semester IV
4.6 Modules and Packages

📌 Definition — Module

A Python file (.py) containing functions, classes, and variables that can be imported and
reused in other programs.

Import syntax:
import module_name
import module_name as alias
from module_name import function_name

📌 Definition — Package

A DIRECTORY (folder) containing multiple modules and a special __init__.py file.


Packages help organise large projects into logical groups.

myapp/
__init__.py
[Link]
[Link]
database/
__init__.py
[Link]

▶ Built-in Modules: math, random, datetime


# ── math module
───────────────────────────────────────────────
import math
print([Link]) # 3.14159...
print([Link](144)) # 12.0
print([Link](4.2)) # 5 (round up)
print([Link](4.8)) # 4 (round down)
print([Link](6)) # 720

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 12 of 15
Python Programming BCA Semester IV
print([Link](1000, 10)) # 3.0 (log base 10)
print([Link](48, 18)) #6

# ── random module
─────────────────────────────────────────────
import random
print([Link](1, 100)) # Random int 1-100
print([Link]()) # Random float 0.0-1.0
print([Link](['A','B','C','D'])) # Random choice
lst = [1, 2, 3, 4, 5]
[Link](lst); print(lst) # Shuffled list
print([Link](range(1,50), 6)) # Lottery numbers

# ── datetime module
───────────────────────────────────────────
import datetime
today = [Link]()
now = [Link]()
print(f'Today : {today}') # 2024-01-15
print(f'Now : {[Link]("%d-%m-%Y %H:%M:%S")}') # Formatted

# Calculate age
dob = [Link](2003, 8, 15)
age = (today - dob).days // 365
print(f'Age : {age} years')

# Days until next exam


exam = today + [Link](days=30)
print(f'Exam in 30 days: {exam}')

▶ Creating a Custom Module


# Creating your own module (save as [Link])
# ── File: [Link]
───────────────────────────────────────────
PI = 3.14159

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 13 of 15
Python Programming BCA Semester IV
def circle_area(radius):
return PI * radius ** 2

def percentage(obtained, total=100):


return (obtained / total) * 100 if total != 0 else 0

def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True

# ── File: [Link] (using the module) ──────────────────────────


import mymath

print(mymath.circle_area(7)) # 153.94
print([Link](85)) # 85.0
print(mymath.is_prime(17)) # True
print(mymath.is_prime(20)) # False

📝 Expected Exam Questions (Based on Marks Pattern)

✏ 2-Mark Questions (Short Answer — 4 to 6 lines each)

Q1. What is OOP? List the four pillars of OOP.


Q2. What is the difference between a class and an object? Give a real-world example.
Q3. What is encapsulation? How is a private attribute defined in Python?
Q4. What is inheritance? What is the use of super() in Python?
Q5. What is polymorphism? Give one example with explanation.
Q6. What is the difference between a module and a package?
Q7. What is method overriding? Give an example.
Q8. What are the five types of inheritance? Briefly explain any two.

📄 5-Mark Questions (Medium Answer — about 1 page each)

Q1. Explain classes and objects with a program: create a Student class with attributes

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 14 of 15
Python Programming BCA Semester IV
(name, USN, marks) and methods (add_marks, average, grade, display).
Q2. Explain encapsulation with a Python program: BankAccount class with private
balance, getters, deposit, and withdraw methods.
Q3. Explain inheritance with programs showing single, multiple, and multilevel
inheritance.
Q4. Explain polymorphism with a program using method overriding in a Shape → Circle,
Rectangle, Triangle hierarchy.
Q5. Explain operator overloading with a Vector class overloading +, -, *, ==, __str__.
Q6. Write programs using built-in modules: math (5 functions), random (lottery, dice),
datetime (age, days until event).

📘 10-Mark Questions (Long Answer — 2 to 3 pages, with full programs)

Q1. Explain all OOP concepts (class, object, encapsulation, inheritance, polymorphism,
abstraction) with programs and real-life examples.
Q2. Write a complete Library Management System using OOP: classes Book, Member,
Library with methods to add books, issue, return, search, display all.
Q3. Write a comprehensive Employee Payroll System: Employee (base), Manager,
Developer, Intern classes with inheritance, method overriding, polymorphism, and
payroll report.
Q4. Explain all 5 types of inheritance with programs and diagrams (draw class
hierarchy).
Q5. Write a Hospital Management System with classes: Patient, Doctor, Appointment —
using encapsulation, inheritance, and polymorphism.

From the desk of Mr. Manjunatha Balluli, SMD College, Ballari Page 15 of 15

You might also like