Guides › Python Programming
Python OOP: Classes, Objects and Inheritance
Master Python object-oriented programming with classes, objects, constructors, inheritance, encapsulation, polymorphism, composition, and practical examples.
Python OOP: Classes, Objects and Inheritance
Object-oriented programming (OOP) is a programming approach that organises code around objects containing data and behaviour. It can help structure larger applications into reusable components.
1. What Is OOP?
OOP models concepts using classes and objects. For example, a student object may store a name and marks and provide methods to calculate results.
The four commonly taught OOP principles are encapsulation, abstraction, inheritance, and polymorphism.
2. Classes and Objects
A class defines a structure; an object is an instance of that class.
class Student:
def __init__(self, name):
self.name = name
def introduce(self):
print(f"Hello, I am {self.name}")
student = Student("Shubham")
student.introduce()
Here, Student is the class, while student refers to an object.
3. The Constructor and self
The __init__ method initialises an object after it is created. The parameter self refers to the current instance.
class Product:
def __init__(self, name, price):
self.name = name
self.price = price
def display(self):
print(self.name, self.price)
item = Product("Keyboard", 1200)
item.display()
4. Instance and Class Attributes
Instance attributes belong to individual objects. Class attributes are shared through the class unless shadowed by an instance attribute.
class Employee:
company = "Codify"
def __init__(self, name):
self.name = name
first = Employee("Asha")
second = Employee("Ravi")
print(first.company)
print(second.name)
Use class attributes for genuinely shared information, not mutable per-instance state.
5. Instance, Class and Static Methods
Instance methods work with a particular object. Class methods receive the class through cls. Static methods are related utility functions that do not automatically receive either an instance or a class.
class Temperature:
unit = "Celsius"
def __init__(self, value):
self.value = value
def display(self):
return f"{self.value} {self.unit}"
@classmethod
def unit_name(cls):
return cls.unit
@staticmethod
def is_valid(value):
return isinstance(value, (int, float))
6. Encapsulation
Encapsulation groups data and behaviour and provides a clear interface for interacting with an object.
Python uses naming conventions and properties rather than enforcing all access restrictions in the same way as some other languages.
class BankAccount:
def __init__(self, balance=0):
self._balance = balance
@property
def balance(self):
return self._balance
def deposit(self, amount):
if amount <= 0:
raise ValueError("Deposit must be positive")
self._balance += amount
This example validates deposits and exposes a read-only balance property.
7. Inheritance
Inheritance allows a class to extend or specialise another class.
class Animal:
def speak(self):
print("Animal sound")
class Dog(Animal):
def speak(self):
print("Woof!")
dog = Dog()
dog.speak()
Use inheritance when there is a meaningful subtype relationship. Avoid deep and complicated inheritance hierarchies.
8. Polymorphism
Polymorphism lets different objects respond to the same operation in their own way.
class Circle:
def area(self):
return 3.14159 * 2 * 2
class Square:
def area(self):
return 4 * 4
for shape in [Circle(), Square()]:
print(shape.area())
Both objects support an area() method, but calculate it differently.
9. Abstraction
Abstraction exposes essential behaviour while hiding implementation details.
Python's abc module supports abstract base classes.
from abc import ABC, abstractmethod
class PaymentMethod(ABC):
@abstractmethod
def pay(self, amount):
pass
class DemoPayment(PaymentMethod):
def pay(self, amount):
print(f"Demo payment: {amount}")
A concrete subclass must implement the abstract method before it can be instantiated.
10. Composition
Composition builds complex objects from simpler objects.
For example, a car can contain an engine object. Composition is often more flexible than inheritance when objects have a component rather than an is-a relationship.
11. Special Methods
Python supports special methods such as __str__, __repr__, __len__, and comparison methods. They allow custom objects to work naturally with built-in operations.
class Book:
def __init__(self, title):
self.title = title
def __str__(self):
return self.title
book = Book("Python Basics")
print(book)
12. OOP Best Practices
- Give classes one clear responsibility.
- Use descriptive names.
- Prefer composition when it simplifies design.
- Avoid unnecessary inheritance.
- Validate object state.
- Write tests for important behaviour.
- Keep public interfaces small and understandable.
13. Practice Projects
- Student management system
- Bank account simulator
- Library management system
- Shopping cart
- Employee payroll calculator
- Vehicle rental system
For each project, identify the objects, their data, their responsibilities, and the relationships between them.
Conclusion
OOP helps structure applications through classes, objects, and clear interfaces. Learn the fundamentals, practise by modelling realistic problems, and use OOP when it improves clarity and maintainability.
More guides
- How to Use Codify: A 7-Day Start Plan — New here? Pick a roadmap, make a study plan, start the DSA sheet, revise with notes, practise for placements and test yourself — one step a day, then a daily routine.
- Infosys Preparation Guide: Online Test, Pseudocode and Interview — Roles (SE, DSE, SP), what each section of the Infosys online test checks, how to crack pseudocode and reasoning, a 4-week plan and the interview.
- Wipro Elite NLTH Preparation: Aptitude, Essay and Coding — The Wipro fresher test round by round — quant, logical and verbal, the written essay, two coding problems — plus a 3-week plan and interview tips.
- Accenture Preparation Guide: Cognitive, Technical, Coding and Communication — Every Accenture round explained — cognitive, MS Office/networking/cloud technical MCQs, pseudocode, coding and the spoken-English test — with a 4-week plan.