EduArn – Online & Offline Training with Free LMS for Python, AI, Cloud & More

Showing posts with label Python OOP. Show all posts
Showing posts with label Python OOP. Show all posts

Python OOP Explained: Classes, Objects, Inheritance, Polymorphism & Encapsulation with Examples (2026 Interview Guide)

Python Object-Oriented Programming (OOP) tutorial explaining Classes, Objects, Inheritance, Polymorphism, and Encapsulation with real-world examples.


Master Python Object-Oriented Programming (OOP) with simple explanations, real-world examples, interview questions, and coding examples.

Python is one of the most popular programming languages for AI, Machine Learning, Data Engineering, Automation, Web Development, and Cloud Computing. One of the most important concepts every Python developer must understand is Object-Oriented Programming (OOP).

Whether you're preparing for interviews at startups, MNCs, or product-based companies, OOP questions are almost guaranteed.

In this guide, you'll learn:

  • What is a Class in Python?

  • What is an Object?

  • What is Inheritance?

  • What is Polymorphism?

  • What is Encapsulation?

  • Real-world examples

  • Interview questions and answers

  • Common mistakes beginners make


What is Object-Oriented Programming (OOP)?

Object-Oriented Programming is a programming paradigm that organizes code into objects. An object contains:

  • Data (Attributes)

  • Functions (Methods)

Think of it like the real world.

Everything around us is an object.

Examples:

  • Car

  • Student

  • Employee

  • Mobile Phone

  • Bank Account

Each object has:

Attributes

  • Name

  • Color

  • Price

Behaviors

  • Start

  • Stop

  • Drive

Python allows us to model these real-world entities using classes.


What is a Class in Python?

A Class is a blueprint or template used to create objects.

Think of it this way:

Class = Blueprint

Object = Real Product

Real-World Example

Imagine a car factory.

The design of a Toyota Fortuner is the class.

Every Fortuner manufactured is an object.

Python Example

class Car:

    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def display(self):
        print(self.brand, self.color)


car1 = Car("BMW", "Black")
car2 = Car("Tesla", "White")

car1.display()
car2.display()

Output

BMW Black
Tesla White

Interview Answer

Question

What is a class?

Answer

A class is a blueprint used to create objects. It defines the attributes and methods that objects created from it will have.


What is an Object?

An object is an instance of a class.

Example

Class

Car

Objects

BMW

Tesla

Toyota

Every object has its own data.


What is Inheritance?

Inheritance allows one class to inherit properties and methods from another class.

It promotes:

  • Code reuse

  • Maintainability

  • Scalability


Real-World Example

Parent

Vehicle

Child Classes

  • Car

  • Bike

  • Truck

Every vehicle can:

  • Start

  • Stop

But each vehicle behaves differently.


Python Example

class Vehicle:

    def start(self):
        print("Vehicle is starting")


class Car(Vehicle):

    def drive(self):
        print("Car is driving")


obj = Car()

obj.start()
obj.drive()

Output

Vehicle is starting
Car is driving

Interview Answer

Question

What is inheritance?

Answer

Inheritance is a mechanism where one class acquires the properties and methods of another class, reducing code duplication and improving code reusability.


What is Method Overriding?

Method overriding occurs when the child class provides its own implementation of a method already defined in the parent class.

Example

class Vehicle:

    def start(self):
        print("Vehicle Started")


class Tesla(Vehicle):

    def start(self):
        print("Tesla starts silently")


car = Tesla()

car.start()

Output

Tesla starts silently

What is Polymorphism?

The word Polymorphism means

One Interface, Multiple Forms

The same method behaves differently depending on the object.


Real-World Example

Imagine pressing the Power button.

TV

Turns On

Laptop

Boots Windows

Phone

Starts Android

Same action.

Different behavior.


Python Example

class Car:

    def start(self):
        print("Starting Car")


class Tesla(Car):

    def start(self):
        print("Tesla starts silently")


class BMW(Car):

    def start(self):
        print("BMW starts with engine sound")


cars = [Tesla(), BMW()]

for car in cars:
    car.start()

Output

Tesla starts silently
BMW starts with engine sound

Interview Answer

Question

What is polymorphism?

Answer

Polymorphism allows the same method or interface to perform different actions depending on the object invoking it.


What is Encapsulation?

Encapsulation means wrapping data and methods together into a single unit (class) while restricting direct access to certain data.

Python uses naming conventions (such as a leading double underscore) to indicate attributes that should not be accessed directly from outside the class.


Real-World Example

Think about your ATM card.

You enter your PIN.

You can withdraw money.

But you cannot directly change your account balance.

The internal implementation is hidden.


Python Example

class BankAccount:

    def __init__(self):
        self.__balance = 10000

    def deposit(self, amount):
        self.__balance += amount

    def get_balance(self):
        return self.__balance


account = BankAccount()

account.deposit(5000)

print(account.get_balance())

Output

15000

Notice that __balance is intended to be accessed through methods rather than directly.


Interview Answer

Question

What is encapsulation?

Answer

Encapsulation is the process of combining data and methods into a single class while controlling access to the internal data through well-defined methods.


Difference Between Inheritance and Polymorphism

InheritancePolymorphism
Reuses code from another classAllows the same method to have different behavior
Parent-child relationshipOne interface, many implementations
Achieved using inheritanceCommonly achieved using method overriding

Difference Between Overloading and Overriding

OverloadingOverriding
Python doesn't support traditional method overloading       Fully supported
Simulated using default arguments or *args       Child class replaces parent method
Same class       Parent and child classes


 

Top Python OOP Interview Questions

1. What is a class?

A blueprint for creating objects.


2. What is an object?

An instance of a class.


3. What is inheritance?

A mechanism where one class inherits properties and methods from another class.


4. What is polymorphism?

The same method behaves differently depending on the object.


5. What is encapsulation?

Bundling data and methods together while controlling access to internal data.


6. What is the difference between abstraction and encapsulation?

  • Encapsulation focuses on restricting access to data and exposing controlled operations.

  • Abstraction focuses on hiding implementation details and exposing only the necessary functionality.


Common Mistakes Beginners Make

  • Confusing a class with an object.

  • Assuming inheritance automatically changes parent behavior (it doesn't unless you override methods).

  • Thinking polymorphism only exists in Python (it's a core OOP concept across many languages).

  • Accessing internal attributes directly instead of using class methods.

  • Memorizing definitions without practicing code.


Final Thoughts

Learning Object-Oriented Programming is essential for becoming a professional Python developer. Classes, inheritance, polymorphism, and encapsulation form the foundation of modern software engineering and are widely used in frameworks such as Django, Flask, FastAPI, TensorFlow, and enterprise AI applications.

The best way to master OOP is to build projects, write code daily, and understand how these concepts solve real-world problems rather than simply memorizing definitions.


Learn Python with Eduarn

Whether you're a student, working professional, or corporate team, Eduarn offers hands-on Python and AI training designed for real-world application.

For Individual Learners

  • Python Programming

  • Data Structures & Algorithms

  • Django & FastAPI

  • Data Science with Python

  • AI & Machine Learning

  • Automation using Python

  • Interview Preparation

For Corporate Teams

  • Python for Developers

  • Python for Data Engineering

  • AI & Generative AI with Python

  • Cloud Automation using Python

  • DevOps with Python

  • Enterprise AI Development

  • Customized corporate upskilling programs

At EduArn.com, our focus is practical learning through live projects, coding exercises, and industry-relevant use cases to help learners build job-ready skills.

This format is optimized for search engines with clear headings, interview-focused sections, real-world examples, comparison tables, and practical code samples while naturally introducing Eduarn's retail and corporate training offerings.


 

Dunder Methods in Python | Magic Methods Guide | Eduarn

 

Dunder Methods (Magic Methods) in Python: A Complete Beginner-to-Advanced Guide

Python is known for its clean syntax and powerful object-oriented programming features. One of the most powerful yet often misunderstood concepts is Dunder Methods, also called Magic Methods.

If you've ever wondered how Python knows what to do when you write +, ==, len(), or print() on your custom objects, the answer lies in dunder methods.

In this guide, we'll explore what dunder methods are, why they matter, and how you can use them to build more Pythonic applications.


What Are Dunder Methods?

Dunder stands for Double UNDERscore.

Dunder methods are special methods in Python whose names begin and end with two underscores.

Examples include:

__init__
__str__
__repr__
__len__
__add__
__eq__
__getitem__

These methods are also known as Magic Methods because Python automatically invokes them when certain operations are performed on objects.


Why Are Dunder Methods Important?

Dunder methods allow your custom classes to behave like Python's built-in data types.

For example:

  • + calls __add__()

  • == calls __eq__()

  • len() calls __len__()

  • print() calls __str__()

Without dunder methods, your custom objects would not integrate naturally with Python's built-in functions and operators.


Example 1: init()

The __init__() method is the constructor of a class.

class Student:

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

student = Student("Vinod")
print(student.name)

Output

Vinod

Python automatically executes __init__() when an object is created.


Example 2: str()

The __str__() method defines how an object should appear when printed.

class Student:

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

    def __str__(self):
        return f"Student Name: {self.name}"

student = Student("Vinod")

print(student)

Output:

Student Name: Vinod

Without __str__(), Python would display the object's memory address.


Example 3: repr()

__repr__() provides an official string representation of an object.

class Student:

    def __repr__(self):
        return "Student('Vinod')"

It is mainly used for debugging.


Example 4: len()

You can customize the behavior of the len() function.

class Team:

    def __len__(self):
        return 5

team = Team()

print(len(team))

Output

5

Example 5: add()

Customize the + operator.

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

Example 6: eq()

Control how objects are compared using ==.

class Employee:

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

    def __eq__(self, other):
        return self.salary == other.salary

emp1 = Employee(50000)
emp2 = Employee(50000)

print(emp1 == emp2)

Output

True

Example 7: getitem()

Allows indexing.

class Numbers:

    def __init__(self):
        self.data = [10,20,30]

    def __getitem__(self,index):
        return self.data[index]

nums = Numbers()

print(nums[1])

Output

20

Example 8: setitem()

Customize assignment using indexes.

class Numbers:

    def __init__(self):
        self.data=[10,20,30]

    def __setitem__(self,index,value):
        self.data[index]=value

nums=Numbers()

nums[1]=200

print(nums.data)

Output

[10, 200, 30]

Example 9: iter() and next()

These methods make your class iterable.

class Counter:

    def __init__(self):
        self.num=1

    def __iter__(self):
        return self

    def __next__(self):
        if self.num<=5:
            value=self.num
            self.num+=1
            return value
        raise StopIteration

counter=Counter()

for i in counter:
    print(i)

Output

1
2
3
4
5

Commonly Used Dunder Methods

Dunder MethodTriggered ByPurpose
__init__()Object creationInitialize objects
__str__()print()User-friendly representation
__repr__()repr()Developer representation
__len__()len()Return length
__add__()+Addition
__sub__()-Subtraction
__mul__()*Multiplication
__eq__()==Equality comparison
__lt__()<Less than
__gt__()>Greater than
__getitem__()obj[index]Index access
__setitem__()obj[index]=valueItem assignment
__iter__()for loopIterator creation
__next__()next()Return next item

When Should You Use Dunder Methods?

Use dunder methods when:

  • Building custom Python classes

  • Creating reusable libraries

  • Designing frameworks

  • Developing APIs

  • Implementing data structures

  • Writing production-grade Python applications

They make your classes feel like native Python objects.


Best Practices

  • Implement only the dunder methods your class genuinely needs.

  • Keep each method focused on a single responsibility.

  • Follow Python's data model instead of redefining expected behavior.

  • Prefer readable, maintainable implementations over clever tricks.

  • Use __repr__() for debugging and __str__() for user-friendly output.


Conclusion

Dunder (Magic) Methods are one of Python's most powerful features. They allow your custom classes to interact seamlessly with Python's built-in syntax, operators, and functions.

By mastering methods like __init__(), __str__(), __len__(), __add__(), and __eq__(), you'll write cleaner, more Pythonic, and more maintainable code.

Whether you're preparing for Python interviews or building enterprise applications, understanding dunder methods is an essential skill for every Python developer.


Learn Python and AI with EduArn

Looking to build practical Python and AI skills?

EduArn offers Retail Training and Corporate Training programs designed for students, working professionals, and enterprise teams.

Our training includes:

  • Python Programming

  • Data Structures and Algorithms

  • Object-Oriented Programming

  • Machine Learning

  • Deep Learning

  • Generative AI

  • Prompt Engineering

  • LangChain

  • LangGraph

  • AI Agents

  • MLOps

  • Docker

  • AWS

  • Real-world Capstone Projects

Whether you're an individual looking to upskill or an organization planning to train your workforce, Eduarn provides hands-on, instructor-led learning focused on real-world outcomes.


 

Frequently Asked Questions (FAQs)

1. What are dunder methods in Python?

Dunder methods (short for Double UNDERscore methods) are special methods in Python that begin and end with two underscores, such as __init__() and __str__(). Python automatically calls these methods to define how objects behave with built-in functions and operators.


2. Why are dunder methods called magic methods?

They are called magic methods because Python invokes them automatically behind the scenes when you perform operations like object creation, addition, comparison, iteration, or printing.


3. What is the difference between __str__() and __repr__()?

  • __str__() returns a user-friendly string representation of an object.

  • __repr__() returns a developer-oriented representation, mainly used for debugging and logging.


4. What is the purpose of the __init__() method?

The __init__() method is the constructor in Python. It is automatically executed when an object is created and is used to initialize the object's attributes.


5. How does __eq__() work in Python?

The __eq__() method defines how two objects are compared using the == operator. It allows you to customize equality comparisons based on your class's attributes.


6. Which Python operators use dunder methods?

Many Python operators internally call dunder methods, including:

  • +__add__()

  • -__sub__()

  • *__mul__()

  • ==__eq__()

  • <__lt__()

  • >__gt__()

  • len()__len__()

  • print()__str__()


7. Can I create my own dunder methods?

No. You should only implement the predefined dunder methods provided by Python's data model. Creating custom methods with names like __mymethod__() is discouraged because Python reserves this naming convention for special methods.


8. When should I use dunder methods?

Use dunder methods when developing custom classes that need to work naturally with Python's built-in functions, operators, iteration, indexing, or object comparisons. They are especially useful in object-oriented programming and framework development.


9. Are dunder methods important for Python interviews?

Yes. Questions about __init__(), __str__(), __repr__(), __eq__(), __len__(), and operator overloading are common in Python developer interviews, especially for intermediate and senior roles.


10. Where can I learn Python and dunder methods with hands-on projects?

You can learn Python, Object-Oriented Programming, dunder methods, AI, Machine Learning, LangChain, LangGraph, and Generative AI through Eduarn's Retail Training and Corporate Training programs. The curriculum includes live instructor-led sessions, hands-on projects, and industry-focused learning designed for students, professionals, and enterprise teams.

Keywords: Dunder Methods Python, Magic Methods Python, Python Special Methods, Python OOP, Python Tutorial, Learn Python, Python Training, Corporate Python Training, Retail Python Training, Eduarn Python Course, Python Programming, Python for Beginners.