Student inherits from Person

Python Practice › OOP Programs › Program 28

Student inherits from Person

EasyOOP Programs · 28 of 48

Create a Student class that inherits from Person, adds student_id and grades, and prints name, age and id.

Output
Ravi, 17, ID S-104

Approach

  1. Call super().__init__ for the shared attributes.

Solution

Python
class Person:    def __init__(self, name, age):        self.name, self.age = name, age class Student(Person):    def __init__(self, name, age, student_id, grades):        super().__init__(name, age)        self.student_id = student_id        self.grades = grades     def show(self):        print(f"{self.name}, {self.age}, ID {self.student_id}") Student("Ravi", 17, "S-104", [88, 92]).show()
Output
Ravi, 17, ID S-104

Line by line

Line 7

The parent sets name and age, so that code is not repeated.

Learn the concept

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

More oop programs

← All 48 OOP Programs

Person class

Python Practice › OOP Programs › Program 27

Person class

EasyOOP Programs · 27 of 48

Create a Person class with name and age and a method to print them.

Output
Name: Asha, Age: 29

Approach

  1. Store the attributes and print them in a method.

Solution

Python
class Person:    def __init__(self, name, age):        self.name = name        self.age = age     def show(self):        print(f"Name: {self.name}, Age: {self.age}") Person("Asha", 29).show()
Output
Name: Asha, Age: 29

Learn the concept

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

More oop programs

← All 48 OOP Programs

Circle area and circumference

Python Practice › OOP Programs › Program 26

Circle area and circumference

EasyOOP Programs · 26 of 48

Create a Circle class with a radius and methods for area and circumference.

Output
153.94 43.98

Approach

  1. Use math.pi.

Solution

Python
import math class Circle:    def __init__(self, radius):        self.radius = radius     def area(self):        return round(math.pi * self.radius ** 2, 2)     def circumference(self):        return round(2 * math.pi * self.radius, 2) c = Circle(7)print(c.area(), c.circumference())
Output
153.94 43.98

Learn the concept

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

More oop programs

← All 48 OOP Programs

Rectangle area class

Python Practice › OOP Programs › Program 25

Rectangle area class

EasyOOP Programs · 25 of 48

Write a Python class to calculate the area of a rectangle.

Output
40

Approach

  1. Store length and width; return their product.

Solution

Python
class Rectangle:    def __init__(self, length, width):        self.length = length        self.width = width     def area(self):        return self.length * self.width print(Rectangle(8, 5).area())
Output
40

Learn the concept

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

More oop programs

← All 48 OOP Programs

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