Object-Oriented Programming (OOP) in Python
OOP (Object-Oriented Programming) is a programming approach where we organize programs using classes and objects.
Python supports OOP and provides features such as classes, objects, inheritance, encapsulation, polymorphism, abstraction, constructors, methods, and properties.
1. What is OOP?
OOP stands for Object-Oriented Programming.
Instead of writing a large program only with functions, we can organize related:
- Data
- Variables
- Functions
inside objects.
Real-life example
Think about a Student.
A student has:
Data:
- Name
- Age
- Roll number
- Course
Actions:
- Study
- Attend class
- Take exam
In Python, we can represent this using a class and objects.
2. Class
A class is a blueprint or template for creating objects.
Syntax
class ClassName: # variables # methods pass
Example
class Student: name = "Ram" age = 20
Here, Student is a class.
3. Object
An object is an instance of a class.
class Student: name = "Ram" age = 20 student1 = Student() print(student1.name) print(student1.age)
Output:
Ram 20
Here:
Student
is the class.
student1
is the object.
4. Multiple Objects
One class can create many objects.
class Student: name = "Unknown" student1 = Student() student2 = Student() student1.name = "Ram" student2.name = "Sita" print(student1.name) print(student2.name)
Output:
Ram Sita
The same class is used to create different objects.
5. __init__() Constructor
The __init__() method is commonly used to initialize an object's data.
It runs automatically when an object is created.
class Student: def __init__(self, name, age): self.name = name self.age = age student1 = Student("Ram", 20) print(student1.name) print(student1.age)
Output:
Ram 20
When this runs:
student1 = Student("Ram", 20)
Python automatically calls:
__init__()
6. What is self?
self refers to the current object.
Example:
class Student: def __init__(self, name, age): self.name = name self.age = age
When we create:
student1 = Student("Ram", 20)
Python stores:
student1.name → Ram student1.age → 20
When we create another:
student2 = Student("Sita", 21)
we get:
student2.name → Sita student2.age → 21
self allows each object to maintain its own data.
7. Attributes
Variables associated with a class or object are called attributes.
There are mainly two important types.
Instance Attributes
These belong to individual objects.
class Student: def __init__(self, name, age): self.name = name self.age = age
Here:
self.name self.age
are instance attributes.
Class Attributes
These are shared by objects of the class.
class Student: college = "Gyandev Academy" def __init__(self, name): self.name = name
Now:
student1 = Student("Ram") student2 = Student("Sita") print(student1.college) print(student2.college)
Output:
Gyandev Academy Gyandev Academy
8. Methods
A function defined inside a class is called a method.
class Student: def __init__(self, name): self.name = name def study(self): print(self.name, "is studying") student1 = Student("Ram") student1.study()
Output:
Ram is studying
9. Types of Methods
Python classes commonly use three types of methods:
- Instance methods
- Class methods
- Static methods
9.1 Instance Method
Works with an object.
Uses self.
class Student: def __init__(self, name): self.name = name def display(self): print(self.name) student1 = Student("Ram") student1.display()
9.2 Class Method
Uses cls and works with the class itself.
Use the @classmethod decorator.
class Student: college = "Gyandev Academy" @classmethod def show_college(cls): print(cls.college) Student.show_college()
Output:
Gyandev Academy
9.3 Static Method
A static method doesn't need self or cls.
Use @staticmethod.
class Calculator: @staticmethod def add(a, b): return a + b print(Calculator.add(10, 20))
Output:
30
10. The Four Main Principles of OOP
The four major concepts of OOP are:
- Encapsulation
- Inheritance
- Polymorphism
- Abstraction
These are often called the four pillars of OOP.
11. Encapsulation
Encapsulation means combining data and methods inside a class and controlling access to the data.
Example:
class BankAccount: def __init__(self, balance): self.balance = balance def deposit(self, amount): self.balance += amount def show_balance(self): print(self.balance) account = BankAccount(1000) account.deposit(500) account.show_balance()
Output:
1500
The balance and the methods that operate on it are grouped inside the class.
12. Public, Protected and Private Members
Python uses naming conventions to indicate different levels of access.
Public
Normal variable:
self.name = name
Can be accessed normally:
student.name
Protected
Single underscore:
self._age = age
Example:
class Student: def __init__(self, age): self._age = age
_age means:
This is intended for internal/subclass use.
Python does not strictly prevent access.
Private
Double underscore:
self.__salary = salary
Example:
class Employee: def __init__(self, salary): self.__salary = salary employee = Employee(50000)
Direct access:
print(employee.__salary)
will fail because of name mangling.
You can provide a method:
class Employee: def __init__(self, salary): self.__salary = salary def get_salary(self): return self.__salary employee = Employee(50000) print(employee.get_salary())
Output:
50000
13. Getter and Setter
Getter is used to get a value.
Setter is used to change a value.
class Student: def __init__(self, age): self.__age = age def get_age(self): return self.__age def set_age(self, age): self.__age = age student = Student(20) print(student.get_age()) student.set_age(21) print(student.get_age())
Output:
20 21
14. Property
Python provides @property to create getter/setter-style access.
class Student: def __init__(self, age): self.__age = age @property def age(self): return self.__age @age.setter def age(self, value): self.__age = value student = Student(20) print(student.age) student.age = 21 print(student.age)
Output:
20 21
15. Inheritance
Inheritance allows one class to acquire properties and methods from another class.
The existing class is called the:
Parent/Base/Super class
The new class is called the:
Child/Derived/Sub class
Example
class Animal: def eat(self): print("Animal is eating") class Dog(Animal): def bark(self): print("Dog is barking") dog = Dog() dog.eat() dog.bark()
Output:
Animal is eating Dog is barking
Dog inherited eat() from Animal.
16. Types of Inheritance
Python supports several inheritance structures.
1. Single Inheritance
One parent → one child.
Animal ↓ Dog
class Animal: pass class Dog(Animal): pass
2. Multilevel Inheritance
Parent → Child → Grandchild.
Animal ↓ Mammal ↓ Dog
class Animal: def eat(self): print("Eating") class Mammal(Animal): def walk(self): print("Walking") class Dog(Mammal): def bark(self): print("Barking") dog = Dog() dog.eat() dog.walk() dog.bark()
3. Multiple Inheritance
One child inherits from multiple parents.
Father Mother \ / \ / Child
class Father: def skill1(self): print("Driving") class Mother: def skill2(self): print("Cooking") class Child(Father, Mother): pass child = Child() child.skill1() child.skill2()
Output:
Driving Cooking
4. Hierarchical Inheritance
One parent → multiple children.
Animal / \ Dog Cat
class Animal: def eat(self): print("Eating") class Dog(Animal): def bark(self): print("Barking") class Cat(Animal): def meow(self): print("Meow")
5. Hybrid Inheritance
Combination of two or more inheritance types.
For example, a combination of:
- Multiple inheritance
- Multilevel inheritance
- Hierarchical inheritance
17. #super()
super() is used to access the parent class.
class Animal: def __init__(self, name): self.name = name class Dog(Animal): def __init__(self, name, breed): super().__init__(name) self.breed = breed dog = Dog("Tommy", "Labrador") print(dog.name) print(dog.breed)
Output:
Tommy Labrador
18. Method Overriding
When a child class provides its own version of a parent method, it is called method overriding.
class Animal: def sound(self): print("Animal makes a sound") class Dog(Animal): def sound(self): print("Dog barks") dog = Dog() dog.sound()
Output:
Dog barks
The child's method replaces the behavior inherited from the parent.
19. Polymorphism
Polymorphism means "many forms."
The same method/interface can behave differently for different objects.
class Dog: def sound(self): print("Bark") class Cat: def sound(self): print("Meow") animals = [Dog(), Cat()] for animal in animals: animal.sound()
Output:
Bark Meow
The same:
animal.sound()
produces different results depending on the object.
20. Duck Typing
Python uses a flexible form of polymorphism called duck typing.
The important thing is what an object can do, rather than what type it officially is.
class Dog: def speak(self): print("Bark") class Cat: def speak(self): print("Meow") def make_sound(animal): animal.speak() make_sound(Dog()) make_sound(Cat())
Output:
Bark Meow
21. Method Overloading
In languages such as C++, you can define multiple methods with the same name but different parameters.
Python does not support traditional method overloading in the same way.
This will not create two separate methods:
class Calculator: def add(self, a): return a def add(self, a, b): return a + b
The second add() replaces the first one.
Python commonly achieves similar behavior using:
- Default arguments
*args- Conditional logic
Example:
class Calculator: def add(self, a, b=0): return a + b c = Calculator() print(c.add(10)) print(c.add(10, 20))
Output:
10 30
22. Abstraction
Abstraction means hiding unnecessary implementation details and showing only the important interface.
For example, when you use an ATM, you know:
Withdraw Deposit Check Balance
You don't need to know the internal banking system.
Python provides abstraction using the abc module.
23. Abstract Class
An abstract class is a class that can define methods that child classes must implement.
from abc import ABC, abstractmethod class Animal(ABC): @abstractmethod def sound(self): pass class Dog(Animal): def sound(self): print("Bark") dog = Dog() dog.sound()
Output:
Bark
You cannot normally create an object directly from the abstract class if it has unimplemented abstract methods:
animal = Animal()
24. Abstract Method
An abstract method is declared using:
@abstractmethod
Example:
class Shape(ABC): @abstractmethod def area(self): pass
Every concrete child class must provide its implementation.
25. Special Methods / Magic Methods
Python has special methods surrounded by double underscores.
Examples:
__init__ __str__ __len__ __add__ __eq__
They are often called dunder methods.
__str__()
Controls how an object is represented when converted to a string or printed.
class Student: def __init__(self, name): self.name = name def __str__(self): return self.name student = Student("Ram") print(student)
Output:
Ram
__len__()
Can define what len(object) does.
class Team: def __init__(self, members): self.members = members def __len__(self): return len(self.members) team = Team(["Ram", "Sita", "Hari"]) print(len(team))
Output:
3
26. Operator Overloading
Python allows us to define how operators work with our objects.
For example:
+
can be customized using:
__add__()
Example:
class Number: def __init__(self, value): self.value = value def __add__(self, other): return self.value + other.value a = Number(10) b = Number(20) print(a + b)
Output:
30
Some common operator methods:
| Operator | Method |
|---|---|
+ | __add__() |
- | __sub__() |
* | __mul__() |
/ | __truediv__() |
== | __eq__() |
< | __lt__() |
> | __gt__() |
len() | __len__() |
str() | __str__() |
27. Composition
Composition means creating an object of one class inside another class.
Example:
class Engine: def start(self): print("Engine started") class Car: def __init__(self): self.engine = Engine() def start(self): self.engine.start() car = Car() car.start()
Output:
Engine started
Here:
Car ↓ Engine
The car has an engine.
This is called a has-a relationship.
28. Inheritance vs Composition
Inheritance
Represents:
is-a
Example:
Dog is an Animal
class Dog(Animal): pass
Composition
Represents:
has-a
Example:
Car has an Engine
class Car: def __init__(self): self.engine = Engine()
29. Class Method vs Static Method vs Instance Method
| Type | First parameter | Works mainly with |
|---|---|---|
| Instance method | self | Object |
| Class method | cls | Class |
| Static method | None | Independent operation |
Example:
class Student: college = "Gyandev" def show_name(self): print("Instance method") @classmethod def show_college(cls): print(cls.college) @staticmethod def welcome(): print("Welcome")
30. Complete OOP Example
Here is a simple example combining several OOP concepts:
class Student: college = "Gyandev Academy" def __init__(self, name, age): self.name = name self.age = age def display(self): print("Name:", self.name) print("Age:", self.age) print("College:", self.college) def study(self): print(self.name, "is studying") student1 = Student("Ram", 20) student2 = Student("Sita", 21) student1.display() student1.study() print() student2.display() student2.study()
Output:
Name: Ram Age: 20 College: Gyandev Academy Ram is studying Name: Sita Age: 21 College: Gyandev Academy Sita is studying
31. Main OOP Concepts Summary
| Concept | Meaning |
|---|---|
| Class | Blueprint for objects |
| Object | Instance of a class |
| Attribute | Data belonging to class/object |
| Method | Function inside a class |
| Constructor | Initializes an object |
self | Current object |
| Encapsulation | Bundling and controlling data |
| Inheritance | Reusing parent class features |
| Polymorphism | Same interface, different behavior |
| Abstraction | Hiding implementation details |
| Overriding | Child changes parent method |
| Composition | One object contains another object |
super() | Access parent class |
@classmethod | Method associated with class |
@staticmethod | Independent method inside class |
| Magic method | Special __method__ |
32. OOP Structure to Remember
OOP | +------------+------------+ | | | Class Object Methods | +----+----+ | | Attributes Methods | +-----------------------------+ | | Encapsulation Abstraction | Inheritance | Polymorphism
The easiest way to remember
Class → Blueprint Object → Real thing created from blueprint Attribute → Object's data Method → Object's action Encapsulation → Protect/bundle data Inheritance → Reuse existing class Polymorphism → Same method, different behavior Abstraction → Hide unnecessary details