Employee management system

Python Practice › OOP Programs › Program 18

Employee management system

MediumOOP Programs · 18 of 48

Write a small employee management system with add, raise and report features.

Output
101 Asha   55000
102 Ravi   62000

Approach

  1. Store employees in a dictionary keyed by id.

Solution

Python
class Employee:    def __init__(self, emp_id, name, salary):        self.emp_id, self.name, self.salary = emp_id, name, salary class Company:    def __init__(self):        self.staff = {}     def hire(self, emp):        self.staff[emp.emp_id] = emp     def give_raise(self, emp_id, percent):        emp = self.staff[emp_id]        emp.salary = round(emp.salary * (1 + percent / 100))     def report(self):        for e in self.staff.values():            print(f"{e.emp_id} {e.name:<6} {e.salary}") c = Company()c.hire(Employee(101, "Asha", 50000))c.hire(Employee(102, "Ravi", 62000))c.give_raise(101, 10)c.report()
Output
101 Asha   55000
102 Ravi   62000

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

School management system

Python Practice › OOP Programs › Program 17

School management system

MediumOOP Programs · 17 of 48

Write a small school management system with classes for students and a school.

Output
['Asha', 'Meena']
Topper: Asha

Approach

  1. A Student class holds data; a School class manages a list of students.

Solution

Python
class Student:    def __init__(self, name, grade, marks):        self.name, self.grade, self.marks = name, grade, marks class School:    def __init__(self, name):        self.name = name        self.students = []     def admit(self, student):        self.students.append(student)     def by_grade(self, grade):        return [s.name for s in self.students if s.grade == grade]     def topper(self):        return max(self.students, key=lambda s: s.marks).name school = School("Sunrise Public School")for args in [("Asha", 5, 92), ("Ravi", 6, 81), ("Meena", 5, 88)]:    school.admit(Student(*args))print(school.by_grade(5))print("Topper:", school.topper())
Output
['Asha', 'Meena']
Topper: Asha

Line by line

Lines 10-11

admit adds a student to the school’s list.

Lines 13-17

Queries are methods on the School, so the rest of the program does not need to know how students are stored.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Encapsulation with a private attribute

Python Practice › OOP Programs › Program 16

Encapsulation with a private attribute

EasyOOP Programs · 16 of 48

Write a Python program that demonstrates encapsulation.

Output
1500
False

Approach

  1. Keep the balance in a “private” attribute and change it only through methods.

Solution

Python
class Account:    def __init__(self, balance):        self.__balance = balance     def deposit(self, amount):        if amount > 0:            self.__balance += amount     def balance(self):        return self.__balance a = Account(1000)a.deposit(500)a.deposit(-50)print(a.balance())print(hasattr(a, "__balance"))
Output
1500
False

Line by line

Line 3

Two leading underscores trigger name mangling, so the attribute is hard to reach from outside.

Line 6

The method validates input, so the balance can never be decreased by a negative deposit.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Abstract method

Python Practice › OOP Programs › Program 15

Abstract method

EasyOOP Programs · 15 of 48

Write a Python program with an abstract class and an abstract method.

Output
Paid Rs 499 by UPI
Error: Can't instantiate abstract class Payment without an implementation for abstract method 'pay'

Approach

  1. Inherit from ABC and decorate the method with @abstractmethod.

Solution

Python
from abc import ABC, abstractmethod class Payment(ABC):    @abstractmethod    def pay(self, amount):        ... class UPI(Payment):    def pay(self, amount):        return f"Paid Rs {amount} by UPI" print(UPI().pay(499))try:    Payment()except TypeError as e:    print("Error:", e)
Output
Paid Rs 499 by UPI
Error: Can't instantiate abstract class Payment without an implementation for abstract method 'pay'

Line by line

Lines 4-6

Every subclass must implement pay.

Lines 12-15

The abstract class itself cannot be instantiated.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Method overriding

Python Practice › OOP Programs › Program 14

Method overriding

EasyOOP Programs · 14 of 48

Write a Python program that demonstrates method overriding.

Output
Sending: Hi
Sending: Hi (via email)

Approach

  1. The child defines a method with the same name; super() reuses the parent’s version.

Solution

Python
class Notification:    def send(self, msg):        return f"Sending: {msg}" class EmailNotification(Notification):    def send(self, msg):        return super().send(msg) + " (via email)" print(Notification().send("Hi"))print(EmailNotification().send("Hi"))
Output
Sending: Hi
Sending: Hi (via email)

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Method overloading

Python Practice › OOP Programs › Program 13

Method overloading

MediumOOP Programs · 13 of 48

Write a Python program that shows how to achieve method overloading.

Output
5
9
0

Approach

  1. Python keeps only the last method with a given name, so use default and variable arguments instead.

Solution

Python
class Calculator:    def add(self, *numbers):        return sum(numbers) c = Calculator()print(c.add(2, 3))print(c.add(2, 3, 4))print(c.add())
Output
5
9
0

Line by line

Line 2

*numbers accepts any number of arguments, so one method covers every case.

Tip

functools.singledispatchmethod can choose a method by the type of the first argument when the behaviour must differ by type.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Hierarchical inheritance

Python Practice › OOP Programs › Program 12

Hierarchical inheritance

EasyOOP Programs · 12 of 48

Write a Python program that demonstrates hierarchical inheritance.

Output
I am a Square
I am a Circle

Approach

  1. Several children share one parent.

Solution

Python
class Shape:    def describe(self):        return f"I am a {type(self).__name__}" class Square(Shape):    pass class Circle(Shape):    pass for s in [Square(), Circle()]:    print(s.describe())
Output
I am a Square
I am a Circle

Line by line

Line 3

type(self) is the actual child class, so the shared method gives a different answer for each.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Multilevel inheritance

Python Practice › OOP Programs › Program 11

Multilevel inheritance

EasyOOP Programs · 11 of 48

Write a Python program that demonstrates multilevel inheritance.

Output
4 petrol 300

Approach

  1. A grandchild inherits from a child, which inherits from a parent.

Solution

Python
class Vehicle:    def wheels(self):        return 4 class Car(Vehicle):    def fuel(self):        return "petrol" class SportsCar(Car):    def speed(self):        return 300 s = SportsCar()print(s.wheels(), s.fuel(), s.speed())
Output
4 petrol 300

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Multiple inheritance

Python Practice › OOP Programs › Program 10

Multiple inheritance

EasyOOP Programs · 10 of 48

Write a Python program that demonstrates multiple inheritance.

Output
photo taken | calling
['SmartPhone', 'Camera', 'Phone', 'object']

Approach

  1. A class inherits from two parents; the MRO decides lookup order.

Solution

Python
class Camera:    def photo(self):        return "photo taken" class Phone:    def call(self):        return "calling" class SmartPhone(Camera, Phone):    pass s = SmartPhone()print(s.photo(), "|", s.call())print([c.__name__ for c in SmartPhone.__mro__])
Output
photo taken | calling
['SmartPhone', 'Camera', 'Phone', 'object']

Line by line

Line 13

The method resolution order shows Python searches SmartPhone, then Camera, then Phone.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs

Single inheritance

Python Practice › OOP Programs › Program 9

Single inheritance

EasyOOP Programs · 9 of 48

Write a Python program that demonstrates single inheritance.

Output
eating and barking

Approach

  1. The child class lists one parent class in brackets.

Solution

Python
class Animal:    def eat(self):        return "eating" class Dog(Animal):    def bark(self):        return "barking" d = Dog()print(d.eat(), "and", d.bark())
Output
eating and barking

Line by line

Line 5

Dog(Animal) gives Dog everything Animal has.

Learn the concept

New to this topic? Read the lesson, then come back.

More oop programs

← All 48 OOP Programs