
Quick answer: Object-oriented programming (OOP) in Python organises code into classes (blueprints) and objects (instances). The four main OOPs concepts are encapsulation (bundling data and methods, hiding internal details), inheritance (a child class reusing a parent class), polymorphism (the same method name behaving differently for different classes) and abstraction (exposing only essential behaviour through abstract classes). Supporting ideas include constructors (__init__), self, class and static methods, and dunder methods such as __str__ and __add__.
All code examples were run on Python 3.13; the outputs shown are real.
Contents
- Class and Object
- Inheritance
- Polymorphism
- Encapsulation
- Abstraction
- Class Variables, Class Methods and Static Methods
- Dunder (Magic) Methods and Operator Overloading
- OOPs Concepts Summary
Class and Object
A class defines attributes and methods; an object is created from it. __init__ is the constructor that runs when an object is created, and self refers to that object.
class Beam:
def __init__(self, length, load):
self.length = length
self.load = load
def max_moment(self):
# simply supported beam with central point load
return self.load * self.length / 4
b = Beam(4, 1000)
print(b.length, b.max_moment())Output:
4 1000.0
Inheritance
A child class inherits attributes and methods from a parent class. super() calls the parent’s methods.
class Vehicle:
def __init__(self, name, wheels):
self.name = name
self.wheels = wheels
def info(self):
return f"{self.name} has {self.wheels} wheels"
class Car(Vehicle):
def __init__(self, name):
super().__init__(name, 4)
class Bike(Vehicle):
def __init__(self, name):
super().__init__(name, 2)
print(Car("Sedan").info())
print(Bike("Sport").info())Output:
Sedan has 4 wheels Sport has 2 wheels
Types of inheritance in Python: single, multiple, multilevel, hierarchical and hybrid.
Polymorphism
Different classes provide their own version of the same method (method overriding), so one loop can handle all of them.
class Shape:
def area(self):
return 0
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return round(3.1416 * self.r ** 2, 2)
class Rectangle(Shape):
def __init__(self, w, h):
self.w, self.h = w, h
def area(self):
return self.w * self.h
for s in [Circle(2), Rectangle(3, 4)]:
print(type(s).__name__, s.area())Output:
Circle 12.57 Rectangle 12
Encapsulation
Encapsulation keeps data safe inside the object. A double underscore makes an attribute private (name-mangled), and @property gives controlled read access.
class Account:
def __init__(self, balance):
self.__balance = balance
@property
def balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
acc = Account(500)
acc.deposit(200)
print(acc.balance)
try:
print(acc.__balance)
except AttributeError:
print("Private attribute cannot be accessed directly")Output:
700 Private attribute cannot be accessed directly
Abstraction
An abstract class (from the abc module) defines methods that child classes must implement. You cannot create an object of the abstract class itself.
from abc import ABC, abstractmethod
class Engine(ABC):
@abstractmethod
def start(self):
pass
class DieselEngine(Engine):
def start(self):
return "Compression ignition start"
print(DieselEngine().start())
try:
Engine()
except TypeError:
print("Cannot create an object of an abstract class")Output:
Compression ignition start Cannot create an object of an abstract class
Class Variables, Class Methods and Static Methods
A class variable is shared by all objects. @classmethod receives the class (useful for alternative constructors); @staticmethod is a plain function grouped inside the class.
class Material:
count = 0
def __init__(self, name):
self.name = name
Material.count += 1
@classmethod
def steel(cls):
return cls("Steel")
@staticmethod
def mpa_to_pa(v):
return v * 1e6
m = Material.steel()
print(m.name, Material.count, Material.mpa_to_pa(250))Output:
Steel 1 250000000.0
Dunder (Magic) Methods and Operator Overloading
Methods like __add__ and __str__ let objects work with + and print().
class Vector:
def __init__(self, x, y):
self.x, self.y = x, y
def __add__(self, other):
return Vector(self.x + other.x, self.y + other.y)
def __str__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4))Output:
Vector(4, 6)
OOPs Concepts Summary
| Concept | Meaning | Python feature |
|---|---|---|
| Class / Object | Blueprint and its instance | class, __init__, self |
| Encapsulation | Hide internal data | _name, __name, @property |
| Inheritance | Reuse parent code | class Child(Parent), super() |
| Polymorphism | Same interface, different behaviour | Method overriding, duck typing, operator overloading |
| Abstraction | Show only essentials | abc.ABC, @abstractmethod |
Frequently Asked Questions
What are the four OOPs concepts in Python?
Encapsulation, inheritance, polymorphism and abstraction, built on classes and objects.
What is self in Python?
self refers to the current object. It is the first parameter of instance methods and is used to access the object’s attributes and methods.
Does Python support multiple inheritance?
Yes. A class can inherit from more than one parent class; Python uses the Method Resolution Order (MRO) to decide which method to call.
Does Python support method overloading?
Not in the traditional sense – a later definition replaces an earlier one. Default arguments and *args are used instead. Operator overloading is supported through dunder methods.
Are private variables truly private in Python?
No. A double underscore only name-mangles the attribute (e.g., _Account__balance). Privacy in Python is mainly by convention.
Related Python Guides
- Python interview questions
- Python programs with output
- Python MCQ quiz
- Python notes PDF
- All Python tutorials
Learn Python With Guidance
Join our Python course or message us on WhatsApp for doubt-clearing and project support.