Create classes, objects, constructors and instance attributes.
ποΈ Object-Oriented Python
Model real entities as cooperating objects that combine data with behavior and grow safely through inheritance, composition and polymorphism.
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def result(self):
return "Pass" if self.marks >= 40 else "Fail"By the End of This Level
You will be able to design small object-oriented Python solutions.
Protect state through clear methods and controlled access.
Reuse and specialise behaviour through inheritance.
Apply overriding, polymorphism and composition appropriately.
Classes and Objects
A class describes a category of objects; an object is one concrete instance created from that class.
A class groups related data and functions under one name. Attributes represent state, while methods represent actions that use or change that state.
A runtime value with its own identity, type and state. Multiple objects from the same class can store different attribute values.
Create Two Student Objects
class Student:
pass
first = Student()
second = Student()
print(type(first) == type(second))True
__init__, self and Attributes
Python calls __init__ after creating an instance so its starting state can be established.
| Part | Purpose | Example |
|---|---|---|
__init__ | Initialises a new instance | def __init__(self, name): |
self | Refers to the current instance | self.name |
| Instance attribute | Stores per-object state | self.marks = marks |
| Object creation | Calls the class | Student("Asha", 88) |
self is explicitPython supplies the current object automatically during a method call, but the method definition must declare self as its first parameter.
Instance Methods
An instance method receives self and performs work using the current objectβs attributes.
Calculate a Rectangleβs Area
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
box = Rectangle(8, 5)
print("Area =", box.area())Area = 40
box.area() is conceptually similar to Rectangle.area(box); the instance becomes the self argument.
Encapsulation and Properties
Encapsulation keeps state and the rules that protect it together inside a class.
Non-public attribute
A leading underscore communicates that an attribute is an internal implementation detail.
self._balance = 0Controlled access
@property exposes method logic through attribute-like syntax and can validate assignments.
@property
def balance(self):
return self._balanceA double-leading name such as self.__pin is transformed to reduce accidental access; it does not provide security or true privacy.
Class Attributes, Class Methods and Static Methods
Class members belong to the class itself and support information or behaviour shared across instances.
| Member | First parameter | Typical use |
|---|---|---|
| Instance method | self | Read or change one object |
| Class method | cls | Alternative constructor or class-level operation |
| Static method | None supplied automatically | Related utility that needs no instance or class state |
| Class attribute | Not applicable | Shared constant or counter |
Track a Shared School Name
class Student:
school = "CodeBhavya Academy"
def __init__(self, name):
self.name = name
student = Student("Bhavya")
print(student.school)CodeBhavya Academy
Inheritance and super()
Inheritance creates a specialised class from an existing class when a genuine βis-aβ relationship exists.
super()Reuse base setupSpecialise an Employee
class Employee:
def __init__(self, name):
self.name = name
class Developer(Employee):
def __init__(self, name, language):
super().__init__(name)
self.language = languageDeveloper is an Employee
Method Overriding and Polymorphism
A subclass overrides a method by defining a method with the same name but specialised behaviour.
Specialise inherited behaviour
A subclass supplies its own implementation while keeping the method name expected by callers.
class Dog:
def speak(self):
return "Woof"Program to behaviour
Different objects respond to the same operation, allowing callers to work with a common interface.
for animal in animals:
print(animal.speak())Python often cares about the behaviour an object provides rather than requiring it to inherit from one particular base class.
Composition
Composition places one object inside another when the relationship is naturally βhas-aβ.
Is-a relationship
A Developer is an Employee. Use inheritance when the subtype can safely replace the base type.
Has-a relationship
A Car has an Engine. Delegate work to the contained object instead of forcing an unrelated class hierarchy.
Flexible
Components can be replaced independently.
Testable
Each collaborator can be tested alone.
Maintainable
Responsibilities stay clearly separated.
Reusable
One component can serve many owners.
Object-Oriented Errors to Avoid
selfInstance methods must declare self first and use it to access instance state.
Put per-object lists and dictionaries inside __init__, not directly on the class.
Inheritance should represent a valid substitutable βis-aβ relationship.
Use methods or properties when an attribute must obey validation rules.
π Object-Oriented Python β Quick Revision
Review these ten rules before attempting the quiz and programming problems.
A class describes the state and behaviour of objects.
An object is one instance of a class.
__init__ establishes an instanceβs initial state.
self refers to the current instance.
Instance attributes store per-object values.
Class attributes are shared through the class.
Encapsulation keeps state and its rules together.
Inheritance models a substitutable βis-aβ relationship.
Overriding gives a subclass specialised behaviour.
Composition models a flexible βhas-aβ relationship.
π§ Level 11 Quiz
Select one answer for each question, then check your score.
1. What does self refer to inside an instance method?
2. Which method normally establishes an objectβs initial attributes?
3. Which member is normally shared by all instances?
4. What does super() help a subclass do?
5. Which concept allows different objects to respond to the same method name?
6. A car containing an engine is primarily which relationship?
π» CodeBhavya Object-Oriented Challenges
Design each class and run it in the browser. The checker uses the displayed input and exact expected output.
Create a Student class that stores a name and marks and returns Pass for marks of at least 40.
Bhavya, 78Expected output: Bhavya: Pass__init__ and let result() return one classification string.Python Code Editor
Program Output
Run your program to see the output.
Test Case
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def result(self):
if self.marks >= 40:
return "Pass"
return "Fail"
name = input()
marks = int(input())
student = Student(name, marks)
print(student.name + ":", student.result())Create a rectangle object with separate methods that return its area and perimeter.
8, 5Expected output: Area = 40 and Perimeter = 26self.length and self.width without requesting new input.Python Code Editor
Program Output
Run your program to see the output.
Test Case
class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * (self.length + self.width)
length = int(input())
width = int(input())
box = Rectangle(length, width)
print("Area =", box.area())
print("Perimeter =", box.perimeter())Store a starting balance, deposit an amount and withdraw an amount only when sufficient funds are available.
1000, 500, 300Expected output: Balance = 1200deposit() add to self.balance and let withdraw() check the amount before subtracting.Python Code Editor
Program Output
Run your program to see the output.
Test Case
class BankAccount:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount <= self.balance:
self.balance -= amount
balance = int(input())
deposit = int(input())
withdraw = int(input())
account = BankAccount(balance)
account.deposit(deposit)
account.withdraw(withdraw)
print("Balance =", account.balance)Create Employee and Developer classes. Reuse the base constructor and return a developer summary.
Asha, 60000, PythonExpected output: Asha | 60000 | Pythonsuper().__init__(name, salary) before storing the language on the developer.Python Code Editor
Program Output
Run your program to see the output.
Test Case
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
class Developer(Employee):
def __init__(self, name, salary, language):
super().__init__(name, salary)
self.language = language
def details(self):
return self.name + " | " + str(self.salary) + " | " + self.language
name = input()
salary = int(input())
language = input()
developer = Developer(name, salary, language)
print(developer.details())Override area() in rectangle and square subclasses, then call the same method on both objects.
6, 4, 5Expected output: Rectangle = 24 and Square = 25area() method; the caller should not need different calculation function names.Python Code Editor
Program Output
Run your program to see the output.
Test Case
class Shape:
def area(self):
return 0
class Rectangle(Shape):
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
class Square(Shape):
def __init__(self, side):
self.side = side
def area(self):
return self.side * self.side
length = int(input())
width = int(input())
side = int(input())
rectangle = Rectangle(length, width)
square = Square(side)
print("Rectangle =", rectangle.area())
print("Square =", square.area())π― Give Every Object a Clear Responsibility
Store meaningful attributes.
Keep rules in methods.
Inherit only for βis-aβ.
Connect focused objects.
π¬ Object Creation β Visual Flow
Follow a class call as Python creates, initialises and returns a usable object.
ποΈ How an Object Is Created
__init__βStore AttributesβReturn Object1. Call the Class
The expression Student("Bhavya", 78) asks the class to create a new instance.
π Program Tracing β Constructor and Method Call
Trace a rectangle object from class call through attribute storage and area calculation.
Click Next to begin tracing.
β
π€ Object-Oriented Python β Interview Questions
Answer aloud before opening each explanation.
What is the difference between a class and an object?
A class is a reusable description of state and behaviour. An object is one runtime instance with its own identity and instance attributes.
Why is self required in instance method definitions?
self gives the method access to the particular object on which it was called, including that objectβs attributes and other methods.
How do instance attributes and class attributes differ?
Instance attributes belong to one object and normally live in its instance namespace. Class attributes belong to the class and are shared through class lookup.
What is method overriding?
Method overriding occurs when a subclass defines a method with the same name as an inherited method to provide specialised behaviour.
When should composition be preferred over inheritance?
Prefer composition for βhas-aβ relationships, when components should be replaceable, or when a subtype cannot safely substitute for the proposed base class.
What does polymorphism improve in a program?
Polymorphism lets callers use one expected operation with different object types, reducing type-specific branching and improving extensibility.
π‘ Object-Oriented Python β Extra Tips
- 01
Name classes with nouns in PascalCase, such as
BankAccount. - 02
Keep methods small and focused on the responsibility of their class.
- 03
Create per-object mutable attributes inside
__init__. - 04
Expose behaviour instead of asking callers to manipulate internal state directly.
- 05
Use
super()so cooperative inheritance follows Pythonβs method resolution order. - 06
Prefer composition when collaborators may change independently.
βοΈ Object-Oriented Python β Extra Practice Questions
- Create a
Bookclass with title, author and a display method. - Build a
Circleclass that returns area and circumference. - Add controlled deposit and withdrawal methods to an account.
- Use a class attribute to count how many objects were created.
- Create a class method that builds a student from a comma-separated string.
- Validate an age assignment using a property setter.
- Derive
CarandBikefrom aVehicleclass. - Override a
fare()method for bus and taxi objects. - Model a computer that contains processor and memory objects.
- Explain why an unrelated helper class should not inherit only for code reuse.
Object-Oriented Python Complete
When you can design classes, protect instance state and explain inheritance, overriding, polymorphism and composition, mark this level complete and continue.
