Object-Oriented Programs
classes, inheritance, a singleton nobody asked for. Read __init__ twice.
25 programs · open one, then the next
Start with Create Class & Object- 01Create Class & ObjectBeginner__init__ runs when you call Student(...). display_info is just a function with self already filled in.Open example →py# Program to create a simple class and object class Student: def __init__(self, name, roll_no):
- 02Instance vs Class VariablesBeginnercount lives on the class. id lives on each object. Change count once, every instance sees it.Open example →py# Program to demonstrate instance vs class variables class Counter: count = 0 # class variable
- 03Constructors in Python ClassesBeginnerUse the __init__ constructor to initialize new objects with default and custom values.Open example →py# Program to demonstrate constructors class Rectangle: def __init__(self, width=1, height=1):
- 04Single InheritanceBeginnerDog(Animal) can speak() without defining it. That is the whole inheritance pitch.Open example →py# Program to demonstrate single inheritance class Animal: def speak(self):
- 05Multiple InheritanceIntermediateDuck(Flyer, Swimmer) gets methods from both. MRO decides who wins if names clash.Open example →py# Program to demonstrate multiple inheritance class Flyer: def fly(self):
- 06Multilevel InheritanceBeginnerIllustrate inheritance across multiple levels of a class hierarchy.Open example →py# Program to demonstrate multilevel inheritance class Vehicle: def move(self):
- 07Polymorphism with MethodsBeginnerUse polymorphism by defining the same method name in different classes.Open example →py# Program to demonstrate polymorphism class Cat: def speak(self):
- 08Method Overloading SimulationBeginnerSimulate method overloading using default arguments and *args.Open example →py# Program to simulate method overloading class Adder: def add(self, *args):
- 09Encapsulation with Getters/SettersIntermediateUse properties to encapsulate attribute access with getter and setter logic.Open example →py# Program to demonstrate encapsulation using properties class Account: def __init__(self, balance=0):
- 10Abstraction with ABCIntermediateUse the abc module to define abstract base classes and abstract methods.Open example →py# Program to demonstrate abstraction with ABC from abc import ABC, abstractmethod
- 11Operator OverloadingIntermediateOverload the + operator for a custom class using __add__.Open example →py# Program to demonstrate operator overloading class Vector: def __init__(self, x, y):
- 12Custom IteratorIntermediateImplement a class that can be iterated over using __iter__ and __next__.Open example →py# Program to implement a custom iterator class Countdown: def __init__(self, start):
- 13Class MethodsIntermediateUse @classmethod to create alternative constructors.Open example →py# Program to demonstrate class methods class Employee: def __init__(self, name, salary):
- 14Static MethodsBeginnerUse @staticmethod for utility methods that logically belong to the class but do not use self or cls.Open example →py# Program to demonstrate static methods class MathUtil: @staticmethod
- 15Composition ExampleIntermediateUse composition by placing one object inside another to build complex behavior.Open example →py# Program to demonstrate composition class Engine: def start(self):
- 16Aggregation ExampleIntermediatePass an existing object in. The other class uses it; it does not create it.Open example →py# Program to demonstrate aggregation class Team: def __init__(self, name):
- 17Private VariablesIntermediateUse name-mangling with double underscores to indicate private attributes.Open example →py# Program to demonstrate private variables (name mangling) class Secret: def __init__(self, data):
- 18Magic Methods OverviewIntermediateShow common magic methods like __str__ and __len__.Open example →py# Program to demonstrate some magic methods class BookCollection: def __init__(self, books):
- 19Object CloningIntermediateClone objects using the copy module (shallow and deep copy).Open example →py# Program to demonstrate object cloning import copy
- 20Custom ExceptionsIntermediateDefine and raise custom exception classes in an OOP style.Open example →py# Program to define and use a custom exception class NegativeAgeError(Exception): pass
- 21Class DecoratorIntermediateUse a class as a decorator to wrap functions with additional behavior.Open example →py# Program to demonstrate a simple class decorator class CallLogger: def __init__(self, func):
- 22Prototype PatternIntermediateImplement a simple Prototype pattern by cloning existing objects.Open example →py# Program to implement a simple Prototype pattern import copy
- 23Singleton PatternIntermediateOnly one instance. Call the constructor twice, get the same object back. People overuse this.Open example →py# Program to implement a simple Singleton pattern class Singleton: _instance = None
- 24MRO (Method Resolution Order) DemoIntermediateClassName.__mro__ is the lookup order. Print it when diamond inheritance gets weird.Open example →py# Program to demonstrate method resolution order (MRO) class A: def who_am_i(self):
- 25Polymorphism (Duck Typing)IntermediateUse duck typing to write functions that work with any object having the required method.Open example →py# Program to demonstrate polymorphism via duck typing class FileLogger: def write(self, message):