1. Simple ClassProblem StatementCreate a class called Person with attributes name and age. Create an instance and print the attributes.ApproachDefine a class with __init__ method to initialize attributes.Solutionclass Person: def __init__(self, name, age): self.name = name self.age = age person = Person("Alice", 25) print(person.name, person.age)
2. Class MethodProblem StatementAdd a method called greet() to the Person class that prints "Hello, my name is [name]".ApproachMethods are functions defined inside a class. Use self to access instance attributes.Solution`class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name
3. Rectangle ClassProblem StatementCreate a Rectangle class with width and height attributes. Add methods to calculate area and perimeter.ApproachArea = width * height, Perimeter = 2 * (width + height).Solution`class Rectangle: def __init__(self, width, height): self.width = width self.height = height def area(self): return self.width * self.height def perimeter(self): return 2 * (self.width + self.height) rect = Rectangle(5, 3) print(f"Area: {rect.area()
4. Bank Account ClassProblem StatementCreate a BankAccount class with balance attribute and methods deposit() and withdraw().ApproachInitialize balance in __init__. deposit() adds amount, withdraw() subtracts if sufficient balance.Solution`class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): self.balance += amount print(f"Deposited {amount
5. Class VariablesProblem StatementCreate a Student class with a class variable count that tracks the number of students created.ApproachClass variables are shared by all instances. Increment count in __init__.Solution`class Student: count = 0 def __init__(self, name): self.name = name Student.count += 1 s1 = Student("Alice") s2 = Student("Bob") print(f"Total students: {Student.count
6. String RepresentationProblem StatementAdd __str__ method to the Person class to return a formatted string representation.Approach__str__ is called when you use str() or print() on an object.Solution`class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"Person(name={self.name
7. Inheritance - BasicProblem StatementCreate a Student class that inherits from Person and adds a student_id attribute.ApproachUse class Student(Person) for inheritance. Call super().__init__() to initialize parent attributes.Solutionclass Person: def __init__(self, name, age): self.name = name self.age = age class Student(Person): def __init__(self, name, age, student_id): super().__init__(name, age) self.student_id = student_id student = Student("Alice", 20, "S123") print(student.name, student.student_id)
8. Method OverridingProblem StatementOverride the greet() method in the Student class to include the student ID.ApproachDefine a method with the same name in the child class to override the parent's method.Solution`class Person: def __init__(self, name): self.name = name def greet(self): return f"Hello, I'm {self.name
9. Private AttributesProblem StatementCreate a class with a private attribute (using __) and provide getter and setter methods.ApproachPrefix attribute with __ to make it private. Create methods to access and modify it.Solutionclass Person: def __init__(self, name): self.__name = name def get_name(self): return self.__name def set_name(self, name): self.__name = name person = Person("Alice") print(person.get_name()) person.set_name("Bob") print(person.get_name())
10. Property DecoratorProblem StatementUse @property decorator to create a computed attribute for a Circle class that calculates area.Approach@property allows you to access a method like an attribute.Solution`import math class Circle: def __init__(self, radius): self.radius = radius @property def area(self): return math.pi * self.radius ** 2 circle = Circle(5) print(f"Area: {circle.area
11. Static MethodProblem StatementCreate a Math class with a static method add() that adds two numbers.ApproachUse @staticmethod decorator. Static methods don't need self or cls.Solutionclass Math: @staticmethod def add(a, b): return a + b print(Math.add(5, 3))
12. Class MethodProblem StatementCreate a Person class with a class method from_birth_year() that creates a Person from birth year.ApproachUse @classmethod decorator. Class methods receive cls as first parameter.Solutionfrom datetime import datetime class Person: def __init__(self, name, age): self.name = name self.age = age @classmethod def from_birth_year(cls, name, birth_year): age = datetime.now().year - birth_year return cls(name, age) person = Person.from_birth_year("Alice", 1998) print(person.name, person.age)
13. Multiple InheritanceProblem StatementCreate classes Flyer and Swimmer, then create a Duck class that inherits from both.ApproachList multiple parent classes in parentheses: class Duck(Flyer, Swimmer).Solutionclass Flyer: def fly(self): return "I can fly" class Swimmer: def swim(self): return "I can swim" class Duck(Flyer, Swimmer): pass duck = Duck() print(duck.fly()) print(duck.swim())
14. Abstract Base ClassProblem StatementCreate an abstract Shape class with an abstract method area(). Create Circle and Square subclasses.ApproachUse ABC and @abstractmethod from abc module.Solution`from abc import ABC, abstractmethod import math class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def __init__(self, radius): self.radius = radius def area(self): return math.pi * self.radius ** 2 class Square(Shape): def __init__(self, side): self.side = side def area(self): return self.side ** 2 circle = Circle(5) square = Square(4) print(f"Circle area: {circle.area()
15. Operator OverloadingProblem StatementCreate a Vector class and overload the + operator to add two vectors.ApproachImplement __add__ method to define behavior of + operator.Solution`class Vector: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return Vector(self.x + other.x, self.y + other.y) def __str__(self): return f"Vector({self.x
16. Context ManagerProblem StatementCreate a class that implements context manager protocol with __enter__ and __exit__ methods.Approach__enter__ is called when entering 'with' block, __exit__ when leaving.Solutionclass FileManager: def __init__(self, filename): self.filename = filename self.file = None def __enter__(self): self.file = open(self.filename, 'w') return self.file def __exit__(self, exc_type, exc_val, exc_tb): if self.file: self.file.close() with FileManager('test.txt') as f: f.write('Hello, World!') print("File closed automatically")
17. Iterator ProtocolProblem StatementCreate a class that implements the iterator protocol to iterate over a range of numbers.ApproachImplement __iter__ (returns self) and __next__ (returns next value or raises StopIteration).Solutionclass Counter: def __init__(self, start, end): self.current = start self.end = end def __iter__(self): return self def __next__(self): if self.current > self.end: raise StopIteration self.current += 1 return self.current - 1 for num in Counter(1, 5): print(num)
18. CompositionProblem StatementCreate an Engine class and a Car class that contains an Engine (composition, not inheritance).ApproachComposition means having an object as an attribute rather than inheriting from it.Solution`class Engine: def __init__(self, horsepower): self.horsepower = horsepower def start(self): return "Engine started" class Car: def __init__(self, model, horsepower): self.model = model self.engine = Engine(horsepower) def start(self): return f"{self.model
19. Singleton PatternProblem StatementImplement a Singleton class that ensures only one instance exists.ApproachUse a class variable to store the instance and __new__ method to control instantiation.Solutionclass Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance s1 = Singleton() s2 = Singleton() print(s1 is s2) # True
20. DataclassProblem StatementUse @dataclass decorator to create a Product class with name, price, and quantity attributes.ApproachImport dataclass from dataclasses. It auto-generates __init__, __repr__, etc.Solution`from dataclasses import dataclass @dataclass class Product: name: str price: float quantity: int = 0 def total_value(self): return self.price * self.quantity product = Product("Laptop", 999.99, 5) print(product) print(f"Total value: ${product.total_value()