CDPL Logo
Cinute Digital
Home
ServicesEventMentors
BlogContact

Data Science

  • Data Science - OverviewComprehensive Data Science and AI - Master ProgramMachine Learning and Data Science with PythonDeep Learning, NLP and Generative AIAdvanced Data Science & Machine Learning MasterclassMachine Learning Algorithms using python ProgrammingMachine Learning and Data Visualization using R ProgrammingPython Programming

Artificial Intelligence(AI)

  • Artificial Intelligence (AI) - OverviewPrompt Engineering with Gen AI

Software Testing Courses

  • Software Testing - OverviewManual Software TestingAPI Testing using POSTMAN and RestAPIsDatabase Management System using MySQLETL Testing CourseAdvanced Software TestingAdvanced Automation TestingAdvanced Manual and Automation TestingAdvanced Manual and Automation TestingJava Programming

Digital Marketing

  • Digital Marketing - OverviewDigital Marketing and Analytics - Master ProgramDigital Marketing and AI (For Business Owners)Digital Marketing With AI Bootcamp

Business Development(BI)

  • Business Intelligence (BI) - OverviewAdvanced Data Analytics - Hero ProgramAdvanced Data Analytics with Python LibrariesExcel for Data Analytics & VisualizationData Analytics & Visualization with TableauData Analytics & Visualization with Power BIData Analytics With BI And Big Data Engineering - Master Program

Blogs

  • BlogsSoftware TestingData ScienceWeb DevelopmentAI & Machine LearningDigital Marketing

Services

  • Campus to CorporateCustom TrainingExpert TalksFaculty DevelopmentGovt & Public Sector TrainingIndustrial VisitsInternship ProgramOn Job TrainingShort Term Training Program (STTP)Train the TrainerWorkshops

Certifications and Accreditation

  • AAA CertificationACTD CertificationValidate Your Certificate

Events

  • Business Analytics Course (Aldel Institute)MoU Signing (St. Francis)Job Fair (Nirmala Memorial)Industrial Visit (VIVA Institute)National Conference on AI (MKES)FDP on Power BI & Tableau (Bhavans College)Internship Program (DJ Sanghvi)TechoutsavIndustrial Visit (Thakur College)Placement Drive (Tech Mahindra)

Follow Us On

Follow Us On

Institute

  • HomeCMS LoginMock TestISTQB RegistrationServicesEventsMentorsPlacementsLive JobsJob OpeningsCareersAbout CDPLOur TeamReviewsAffiliate ProgramContact Us

City Wise

Software Testing City Wise

  • Software Testing Course in MumbaiSoftware Testing Course in DelhiSoftware Testing Course in AhmedabadSoftware Testing Course in ChennaiSoftware Testing Course in BengaluruSoftware Testing Course in PuneSoftware Testing Course in KolkataSoftware Testing Course in Hyderabad

Data Science City Wise

  • Data Science Course in MumbaiData Science Course in DelhiData Science Course in AhmedabadData Science Course in ChennaiData Science Course in BengaluruData Science Course in PuneData Science Course in KolkataData Science Course in Hyderabad

Business Intelligence City Wise

  • Business Intelligence Course in MumbaiBusiness Intelligence Course in delhiBusiness Intelligence Course in AhmedabadBusiness Intelligence Course in ChennaiBusiness Intelligence Course in BengaluruBusiness Intelligence Course in PuneBusiness Intelligence Course in KolkataBusiness Intelligence Course in Hyderabad

Artificial Intelligence City Wise

  • Artificial Intelligence Course in MumbaiArtificial Intelligence Course in delhiArtificial Intelligence Course in AhmedabadArtificial Intelligence Course in ChennaiArtificial Intelligence Course in BengaluruArtificial Intelligence Course in PuneArtificial Intelligence Course in KolkataArtificial Intelligence Course in Hyderabad

Digital Marketing City Wise

  • Digital Marketing Course in MumbaiDigital Marketing Course in delhiDigital Marketing Course in AhmedabadDigital Marketing Course in ChennaiDigital Marketing Course in BengaluruDigital Marketing Course in PuneDigital Marketing Course in KolkataDigital Marketing Course in Hyderabad
View All
Cinute Digital logo

Cinute Digital

Get In Touch

Head Office (CDPL)

Office 203 & 204, B-Wing, 1st Floor, Shanti Shopping Centre, Opposite Mira Road Station (E), Mumbai, Maharashtra, 401107

Study Center MeghMehul Classes (Vasai)

Shop No 7, Laxmi Palace, Opposite Vidhyavardhini Degree Engineering College, Gurunanak Nagar, Vasai West, Mumbai, Maharashtra - 401202
contact@cinutedigital.com
+91 78-883-837-88|+91 84-889-889-84
MSME
Skill India
Trustpilot
ISO 27001 Certified
ISO 9001 Certified
Privacy PolicyCookies PolicyTerms and ConditionsCancellation/Refund Policy

ISO 9001:2015 (QMS) 27001:2013 (ISMS) Certified Company.

© 2026 Cinute Digital Pvt. Ltd. — All Rights Reserved.

Powered By

Testriq_logo
All BlogsWeb DevelopmentData SciencePythonPython ProgrammingArtificial Intelligence and Machine Learning (AI/ML)Digital MarketingBusiness Intelligence (BI)Software TestingMachine Learning & PythonArtificial IntelligenceAll Categories

The 4 Pillars of OOPs in Python: Encapsulation, Abstraction, Inheritance & Polymorphism

Rehmat Shaikh
Rehmat Shaikh

A visionary data scientist dedicated to unlocking the potential of data to drive informed decision-making and spark innovation. With a strong foundation in Data Science.

August 31, 2026•5 min read
The 4 Pillars of OOPs in Python: Encapsulation, Abstraction, Inheritance & Polymorphism

The four pillars of OOPs in Python are Encapsulation, Abstraction, Inheritance and Polymorphism. Each explained with runnable code, plus the Python-specific behaviour most tutorials get wrong.

The 4 pillars of OOPs in Python are Encapsulation, Abstraction, Inheritance and Polymorphism. Each one explained with working code examples and the Python-specific catches.

The four pillars of OOPs in Python are Encapsulation, Abstraction, Inheritance and Polymorphism. Every object-oriented language rests on these four ideas, but Python implements some of them very differently from Java or C++ and that difference is exactly where most learners get stuck in interviews.

This guide explains each pillar with code you can run, and flags the Python-specific behaviour that generic OOP tutorials skip.

The four pillars of OOPs in Python - Encapsulation, Abstraction, Inheritance and Polymorphism

First, what does OOP actually mean?

Object-oriented programming organises code around objects bundles of data and the functions that operate on that data instead of loose functions passing values around.

A class is the blueprint. An object is one thing built from it.

class Student:
    def __init__(self, name, course):
        self.name = name
        self.course = course

    def introduce(self):
        return f"{self.name} is learning {self.course}"

s = Student("Aarav", "Python")
print(s.introduce())    # Aarav is learning Python

Student is the class. s is an object. __init__ runs automatically when you create one, and self is how an object refers to itself.

That is the foundation. The four pillars are the principles built on top of it.

Pillar 1: Encapsulation

Encapsulation means keeping an object's data and the methods that change it together, and controlling access to that data from outside.

The idea: an object should protect its own state. Other code asks the object to do something rather than reaching in and editing its variables directly.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance          # double underscore

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self.__balance += amount

    def get_balance(self):
        return self.__balance


acc = BankAccount(1000)
acc.deposit(500)
print(acc.get_balance())    # 1500

Because deposit() guards the value, nobody can set a negative balance by accident. That is encapsulation working.

The Python catch nobody mentions

Here is where Python differs from Java, and where interviewers probe:

Python has no truly private variables. The double underscore does not lock anything it triggers name mangling. Python quietly renames _ _balance to _BankAccount_ _balance.

print(acc.__balance)             # AttributeError
print(acc._BankAccount__balance) # 1500  — still reachable

So the data is discouraged from outside access, not prevented. Python's convention is:

PrefixMeaningEnforced?
namePublic - use freely-
_nameInternal, please don't touchNo, convention only
_ _nameName-mangledNo, just renamed

If someone tells you _ _ makes a variable private in Python, they have learned OOP from a Java tutorial. Say "name mangling" in your interview and you will stand out.

Encapsulation in Python private data accessed only through methods

Pillar 2: Abstraction

Abstraction means exposing what something does while hiding how it does it.

You drive a car without knowing how combustion works. The steering wheel is the interface; the engine is the hidden implementation.

In Python, abstraction is enforced with the abc module:

class TestCase(ABC):

    @abstractmethod
    def run(self):
        """Every test case must define how it runs."""
        pass

    def report(self):                 # shared by all subclasses
        return f"{self.__class__.__name__} finished"


class LoginTest(TestCase):
    def run(self):
        return "Login test passed"


t = LoginTest()
print(t.run())       # Login test passed
print(t.report())    # LoginTest finished

TestCase()           # TypeError — cannot instantiate abstract class
from abc import ABC, abstractmethod

Two things happen here. TestCase cannot be created directly, and any subclass that forgets to define run() fails immediately rather than silently doing nothing.

That last part matters in real projects: the error arrives at the class definition, not three weeks later in production.

Abstraction vs Encapsulation

These two get confused constantly, and it is a standard interview question.

EncapsulationAbstraction
HidesDataComplexity
Question it answers"Who can change this value?""What do I need to know to use this?"
Python tool_ and _ _ prefixesABC, @abstractmethod
One lineProtecting the dataSimplifying the interface

Pillar 3: Inheritance

Inheritance lets one class take on the attributes and methods of another, so shared behaviour is written once.

def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def details(self):
        return f"{self.name} earns {self.salary}"


class Tester(Employee):
    def __init__(self, name, salary, tools):
        super().__init__(name, salary)     # reuse the parent's setup
        self.tools = tools

    def details(self):                     # override
        base = super().details()
        return f"{base} and works with {', '.join(self.tools)}"


t = Tester("Priya", 600000, ["Selenium", "Postman"])
print(t.details())
# Priya earns 600000 and works with Selenium, Postman
class Employee:

super() calls the parent's version. It saves rewriting the parent's logic and keeps behaviour consistent when the parent changes.

Types of inheritance in Python

TypeMeaning
Single One class inherits from one parent
MultilevelA → B → C, a chain
HierarchicalSeveral classes share one parent
MultipleOne class inherits from two or more parents

Python supports multiple inheritance, which Java deliberately does not:

def log(self):
        return f"[LOG] {self.__class__.__name__}"

class Retryable:
    def retry(self):
        return "Retrying..."

class ApiTest(Loggable, Retryable):
    pass

a = ApiTest()
print(a.log())      # [LOG] ApiTest
print(a.retry())    # Retrying...
class Loggable:

When two parents define the same method, Python resolves the conflict using the Method Resolution Order (MRO) left to right through the inheritance chain. You can inspect it:

print(ApiTest.__mro__)

Being able to say "Python handles the diamond problem with MRO, which follows C3 linearisation" is the kind of answer that ends the OOP section of an interview well.

Inheritance in Python - child classes inheriting from a parent class

Pillar 4: Polymorphism

Polymorphism means the same method name behaves differently depending on the object it is called on.

The word means "many forms". One interface, several implementations.

    def execute(self):
        return "Running browser test"

class Postman:
    def execute(self):
        return "Running API test"

class Appium:
    def execute(self):
        return "Running mobile test"


for tool in [Selenium(), Postman(), Appium()]:
    print(tool.execute())
class Selenium:

Output:

Running browser test
Running API test
Running mobile test

The loop never checks which class it is holding. It calls execute() and each object responds in its own way. Add a fourth tool tomorrow and the loop needs no change at all that is the real payoff.

Duck typing Python's version

Notice those three classes share no parent class. In Java you would need a common interface. Python does not care:

If it walks like a duck and quacks like a duck, treat it as a duck.

Python checks whether the object has the method, not what it inherits from. This is called duck typing, and it is the idiomatic Python answer to a polymorphism question.

One more Python difference

Python does not support method overloading the way Java does. Define a method twice and the second definition simply replaces the first:

    def greet(self):
        return "Hello"

    def greet(self, name):        # this one wins
        return f"Hello {name}"

d = Demo()
d.greet()          # TypeError — the first version is gone
class Demo:

The Pythonic approach is default arguments or *args:

    def greet(self, name=None):
        return f"Hello {name}" if name else "Hello"
class Demo:
Polymorphism in Python one method name, different behaviour per class

All four pillars in one example

Here is a small automation framework using every pillar at once close to how real test frameworks are built.

class BaseTest(ABC):                      # ABSTRACTION
    def __init__(self, name):
        self.name = name
        self.__status = "not run"         # ENCAPSULATION

    @abstractmethod
    def execute(self):
        ...

    def set_status(self, value):
        if value not in ("passed", "failed"):
            raise ValueError("Invalid status")
        self.__status = value

    def get_status(self):
        return self.__status


class UITest(BaseTest):                   # INHERITANCE
    def execute(self):
        self.set_status("passed")
        return f"UI test '{self.name}' passed"


class ApiTest(BaseTest):                  # INHERITANCE
    def execute(self):
        self.set_status("failed")
        return f"API test '{self.name}' failed"


suite = [UITest("login"), ApiTest("create-order")]

for test in suite:                        # POLYMORPHISM
    print(test.execute())
    print("  status:", test.get_status())
from abc import ABC, abstractmethod

Output:

UI test 'login' passed
  status: passed
API test 'create-order' failed
  status: failed

Twenty-five lines, all four pillars, and a structure you would genuinely recognise inside a professional test framework.

All four OOPs pillars working together in a Python test framework example

Four mistakes beginners make

1. Thinking _ _ makes something private. It triggers name mangling. The value is still reachable as _ClassName_ _attribute.

2. Forgetting super()._ _init_ _(). Skip it and the parent's attributes never get set, producing an AttributeError far from the actual cause.

3. Building deep inheritance chains. Five levels down, nobody knows where a method comes from. Two or three levels is usually the limit before composition is the better answer.

4. Confusing abstraction with encapsulation. Abstraction hides complexity behind a simple interface. Encapsulation protects data behind methods. Different problems.

Why OOP matters if you are heading into testing

If you are learning Python for QA or automation work, these four ideas are not academic they are the shape of every framework you will touch:

  • Page Object Model, the standard Selenium pattern, is inheritance and encapsulation: one page, one class, its elements kept inside it.
  • Base test classes holding setup and teardown are abstraction.
  • A single suite runner looping over different test types is polymorphism, exactly as in the example above.

This is precisely what separates a manual tester from an SDET a Software Development Engineer in Test writes the framework rather than only using it, and frameworks are built from these four ideas.

If you are starting from zero, our Python course covers OOP from first principles with test-focused examples. If you already know the basics and want to apply them, the automation testing course builds a working framework using these patterns, and the API testing course does the same at the service layer.

Coming from manual testing? Your testing judgement already transfers OOP is the coding layer you are adding on top. Prefer a different language? The same four pillars appear in our Java course, with stricter access control and no multiple inheritance.

If your interest is data rather than testing, OOP shows up just as much in data science and machine learning with Python scikit-learn's entire API is built on classes with a shared interface, which is polymorphism again.

You can see the full range in our software testing course catalogue.

Frequently asked questions

What are the 4 pillars of OOPs in Python?

Encapsulation, Abstraction, Inheritance and Polymorphism. Encapsulation protects data inside an object; Abstraction hides complexity behind a simple interface; Inheritance lets classes reuse behaviour from a parent; Polymorphism lets one method name behave differently across classes.

Is it 4 pillars or 3?

Four is standard. Some older material lists three, treating abstraction as part of encapsulation. Interviews in India almost always expect four name all four.

Does Python have real private variables?

No. A single underscore is a convention, and a double underscore triggers name mangling Python renames _ _x to _ClassName_ _x. It is discouraged from outside access, not blocked.

What is duck typing?

Python's approach to polymorphism: it checks whether an object has the method you are calling, not what class it inherits from. If two unrelated classes both define execute(), both can be used interchangeably.

Does Python support multiple inheritance?

Yes, unlike Java. When parents share a method name, Python resolves it through the Method Resolution Order, which follows C3 linearisation. Check any class's order with ClassName._ _mro_ _.

Do I need OOP for software testing?

For manual testing, no. For automation and SDET roles, yes every major framework is built on classes, and the Page Object Model is inheritance and encapsulation applied directly.

In summary

PillarWhat it doesPython tool
EncapsulationProtects data inside the object_name, _ _name, getters/setters
AbstractionHides complexity behind an interfaceABC, @abstractmethod
InheritanceReuses behaviour from a parentclass Child(Parent), super()
PolymorphismOne name, many behavioursMethod overriding, duck typing

Read them once and they sound abstract. Write the examples above by hand changing the names, breaking them on purpose, seeing what errors appear and they become obvious. That hour is what turns this from a memorised list into something you can actually use.

Tags

#Python#OOPs#Programming#Software Testing#Interview Preparation
Rehmat Shaikh
Rehmat Shaikh

A visionary data scientist dedicated to unlocking the potential of data to drive informed decision-making and spark innovation. With a strong foundation in Data Science.

August 31, 2026•5 min read

Share this article

TwitterLinkedInFacebook

Related Posts

No related posts found.

Categories

Web Development8Data Science17Python1Python Programming2Artificial Intelligence and Machine Learning (AI/ML)2Digital Marketing9Business Intelligence (BI)8Software Testing19Machine Learning & Python1Artificial Intelligence5
View All Categories

Newsletter

Get the latest articles and insights delivered directly to your inbox.

No spam. Unsubscribe anytime.

Popular Tags

#Software Testing#TestAutomation#Python#OOPs#Programming#Interview Preparation#Automated Regression Testing#RegressionTesting#APITesting#TestingCareer

Ready for Career Guidance?

At CDPL Ed-tech Institute, we provide expert career advice and counselling in AI, ML, Software Testing, Software Development, and more. Apply this checklist to your content strategy and elevate your skills. For personalized guidance, book a session today.