Protected and private members

Python Practice › OOP Programs › Program 24

Protected and private members

EasyOOP Programs · 24 of 48

Write a Python program showing protected (_x) and private (__x) members.

Output
asha tester
['name', '_role', '_User__password']

Approach

  1. One underscore is a convention; two underscores trigger name mangling.

Solution

Python
class User:    def __init__(self):        self.name = "asha"        self._role = "tester"        self.__password = "s3cret" u = User()print(u.name, u._role)print([a for a in vars(u)])
Output
asha tester
['name', '_role', '_User__password']

Line by line

Line 9

The private attribute is stored as _User__password, which is why outside code cannot use u.__password.

Learn the concept

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

More oop programs

← All 48 OOP Programs

setattr() and getattr()

Python Practice › OOP Programs › Program 23

setattr() and getattr()

EasyOOP Programs · 23 of 48

Write a Python program that uses setattr() and getattr().

Output
chromium 30
0

Approach

  1. Set and read attributes whose names are stored in strings.

Solution

Python
class Config:    pass cfg = Config()settings = {"browser": "chromium", "headless": True, "timeout": 30}for key, value in settings.items():    setattr(cfg, key, value) print(cfg.browser, getattr(cfg, "timeout"))print(getattr(cfg, "retries", 0))
Output
chromium 30
0

Line by line

Lines 6-7

setattr creates attributes from dictionary keys.

Line 10

getattr with a default does not fail for missing attributes.

Learn the concept

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

More oop programs

← All 48 OOP Programs

Five-level inheritance chain

Python Practice › OOP Programs › Program 22

Five-level inheritance chain

EasyOOP Programs · 22 of 48

Create 5 classes and set up multilevel inheritance among them.

Output
A B C D E
['E', 'D', 'C', 'B', 'A', 'object']

Approach

  1. Each class inherits from the previous one and adds one method.

Solution

Python
class A:    def a(self): return "A"class B(A):    def b(self): return "B"class C(B):    def c(self): return "C"class D(C):    def d(self): return "D"class E(D):    def e(self): return "E" obj = E()print(obj.a(), obj.b(), obj.c(), obj.d(), obj.e())print([cls.__name__ for cls in E.__mro__])
Output
A B C D E
['E', 'D', 'C', 'B', 'A', 'object']

Learn the concept

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

More oop programs

← All 48 OOP Programs

Access five classes through one object

Python Practice › OOP Programs › Program 21

Access five classes through one object

EasyOOP Programs · 21 of 48

Create 5 classes and access them through a single class object (composition).

Output
CPU: 8 cores
RAM: 16 GB
Disk: 512 GB SSD
GPU: integrated
Screen: 15.6 inch

Approach

  1. One Computer object holds an instance of each part class.

Solution

Python
class CPU:    def info(self): return "CPU: 8 cores"class RAM:    def info(self): return "RAM: 16 GB"class Disk:    def info(self): return "Disk: 512 GB SSD"class GPU:    def info(self): return "GPU: integrated"class Screen:    def info(self): return "Screen: 15.6 inch" class Computer:    def __init__(self):        self.parts = [CPU(), RAM(), Disk(), GPU(), Screen()]     def specs(self):        return [p.info() for p in self.parts] for line in Computer().specs():    print(line)
Output
CPU: 8 cores
RAM: 16 GB
Disk: 512 GB SSD
GPU: integrated
Screen: 15.6 inch

Line by line

Lines 12-14

The Computer “has” five parts; this is composition rather than inheritance.

Learn the concept

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

More oop programs

← All 48 OOP Programs

Class in a module, imported elsewhere

Python Practice › OOP Programs › Program 20

Class in a module, imported elsewhere

EasyOOP Programs · 20 of 48

Write a Python class in its own module and import it from another script.

Output
25

Approach

  1. Save the class in shapes.py, then from shapes import Square.

Solution

Python
with open("shapes.py", "w") as f:    f.write("class Square:\n"            "    def __init__(self, side):\n"            "        self.side = side\n"            "    def area(self):\n"            "        return self.side ** 2\n") from shapes import Square print(Square(5).area())
Output
25

Line by line

Lines 1-6

Creates the module file so the example is self-contained; normally you would write shapes.py in your editor.

Line 8

Module-level import makes Square available in this script.

Learn the concept

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

More oop programs

← All 48 OOP Programs

Property decorator

Python Practice › OOP Programs › Program 19

Property decorator

EasyOOP Programs · 19 of 48

Write a Python class that uses @property for a validated attribute.

Output
150
Error: price cannot be negative

Approach

  1. A getter with @property and a setter with @<name>.setter.

Solution

Python
class Product:    def __init__(self, price):        self.price = price     @property    def price(self):        return self._price     @price.setter    def price(self, value):        if value < 0:            raise ValueError("price cannot be negative")        self._price = value p = Product(100)p.price = 150print(p.price)try:    p.price = -1except ValueError as e:    print("Error:", e)
Output
150
Error: price cannot be negative

Line by line

Line 3

Even the constructor goes through the setter, so invalid prices are rejected everywhere.

Learn the concept

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

More oop programs

← All 48 OOP Programs

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