Paramclasses Academy - Blog

Tutorials Details

←
Post 16 of 20
→

Python OOP: Classes, Objects, Inheritance, Encapsulation & Polymorphism

Python OOP: Classes, Objects, Inheritance, Encapsulation & Polymorphism

October 17, 2026

Python OOP: Classes, Objects, Inheritance, Encapsulation & Polymorphism

Introduction to Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming approach that organizes code using classes and objects. It helps developers create reusable, maintainable, and well-structured applications.

Python supports several important OOP concepts, including:

  • Classes and Objects

  • Constructors and the self keyword

  • Instance and Class Variables

  • Methods

  • Inheritance

  • Encapsulation

  • Polymorphism

  • Abstraction

OOP is widely used in web development, software applications, automation tools, and large-scale projects.

1. What Is a Class in Python?

A class is a blueprint for creating objects. It defines the attributes and methods that its objects can have.

Example

class Student:
    name = "Rahul"
    age = 20

    def display(self):
        print(self.name)
        print(self.age)

student1 = Student()
student1.display()

Output

Rahul
20

In this example, Student is a class. It contains two attributes and one method.

2. What Is an Object in Python?

An object is an instance of a class. You can create multiple objects from the same class, and each object can store different data.

Example

class Student:
    def display(self):
        print(self.name, self.age)

student1 = Student()
student1.name = "Rahul"
student1.age = 20

student2 = Student()
student2.name = "Priya"
student2.age = 22

student1.display()
student2.display()

Output

Rahul 20
Priya 22

Here, student1 and student2 are separate objects of the Student class.

3. The __init__() Constructor

The __init__() method initializes an object's attributes when an object is created.

Example

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

    def display(self):
        print(f"Name: {self.name}")
        print(f"Age: {self.age}")

student1 = Student("Rahul", 20)
student1.display()

Output

Name: Rahul
Age: 20

Important points:

  • __init__() is automatically called when an object is created.

  • It is commonly used to initialize object attributes.

  • self refers to the current instance.

  • self.name and self.age store data on that object.

Technically, __init__() initializes an object; object creation itself is handled by __new__().

4. Understanding the self Keyword

The self parameter refers to the current object. It allows instance methods to access and modify that object's attributes.

Example

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

    def show_details(self):
        print(f"Brand: {self.brand}")
        print(f"Color: {self.color}")

car1 = Car("Toyota", "White")
car1.show_details()

Output

Brand: Toyota
Color: White

self is a naming convention rather than a reserved keyword, but it is the standard convention used in Python.

5. Instance Variables and Class Variables

Python classes can contain instance variables and class variables.

Instance variables belong to individual objects. Class variables are shared through the class unless an instance overrides them.

Example

class Employee:
    company = "ABC Technologies"

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

emp1 = Employee("Amit", 30000)
emp2 = Employee("Neha", 40000)

print(emp1.name)
print(emp2.name)
print(Employee.company)

Output

Amit
Neha
ABC Technologies

In this example, name and salary are instance variables, while company is a class variable.

6. Types of Methods in Python

Python classes commonly use three types of methods.

Instance Method

An instance method works with an individual object's data and receives self.

class Student:
    def display(self):
        print("This is an instance method.")

Class Method

A class method receives the class as its first argument, conventionally named cls. It is declared using @classmethod.

class Student:
    school = "ABC School"

    @classmethod
    def show_school(cls):
        print(cls.school)

Student.show_school()

Static Method

A static method does not automatically receive self or cls. It is declared using @staticmethod.

class Calculator:
    @staticmethod
    def add(a, b):
        return a + b

print(Calculator.add(10, 20))

Output:

30

Use instance methods for object data, class methods for class-level operations, and static methods for related utility functions.

7. What Is Inheritance in Python?

Inheritance allows one class to reuse and extend the attributes and methods of another class.

The existing class is called the parent class or base class. The new class is called the child class or derived 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.

The Dog class inherits the eat() method from the Animal class.

Common Types of Inheritance

1. Single Inheritance: One child class inherits from one parent class.

class Animal:
    pass

class Dog(Animal):
    pass

2. Multiple Inheritance: One child class inherits from multiple parent classes.

class Camera:
    def take_photo(self):
        print("Photo captured.")

class Phone:
    def make_call(self):
        print("Calling...")

class Smartphone(Camera, Phone):
    pass

phone = Smartphone()
phone.take_photo()
phone.make_call()

3. Multilevel Inheritance: A class inherits from another derived class.

class Animal:
    pass

class Mammal(Animal):
    pass

class Dog(Mammal):
    pass

4. Hierarchical Inheritance: Multiple child classes inherit from the same parent class.

class Animal:
    def eat(self):
        print("Eating...")

class Dog(Animal):
    pass

class Cat(Animal):
    pass

8. Method Overriding and super()

Method overriding occurs when a child class defines a method with the same name as a method in its parent class.

The super() function allows a child class to access methods from its parent class according to Python's method resolution order.

Example

class Animal:
    def sound(self):
        print("Animals make different sounds.")

class Dog(Animal):
    def sound(self):
        super().sound()
        print("Dog barks.")

dog = Dog()
dog.sound()

Output

Animals make different sounds.
Dog barks.

Method overriding lets child classes customize inherited behavior.

9. Encapsulation in Python

Encapsulation means grouping data and related methods inside a class while controlling how that data is accessed or modified.

Python uses naming conventions and features such as properties to support encapsulation.

Example Using a Property

class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    @property
    def balance(self):
        return self._balance

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount

account = BankAccount(1000)
account.deposit(500)

print(account.balance)

Output

1500

The @property decorator allows balance to be accessed like an attribute while using a method internally.

Understanding Python naming conventions:

  • name: Public attribute.

  • _name: Conventionally intended for internal use.

  • __name: Uses name mangling to reduce accidental name conflicts.

Python does not enforce strict private access in the same way as some other languages. Name mangling is not a security mechanism.

10. Polymorphism in Python

Polymorphism means that the same operation or method name can behave differently depending on the object.

Example

class Dog:
    def sound(self):
        print("Bark")

class Cat:
    def sound(self):
        print("Meow")

def make_sound(animal):
    animal.sound()

make_sound(Dog())
make_sound(Cat())

Output

Bark
Meow

The make_sound() function works with both objects because each provides a compatible sound() method.

This style is an example of duck typing: Python focuses on the operations an object supports rather than requiring a specific class.

11. Abstraction in Python

Abstraction means exposing essential behavior while hiding unnecessary implementation details.

Python provides the abc module for defining abstract base classes.

Example

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def area(self):
        pass

class Rectangle(Shape):
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def area(self):
        return self.length * self.width

rectangle = Rectangle(10, 5)
print(rectangle.area())

Output

50

The Shape class requires its concrete subclasses to implement area(). You cannot normally instantiate Shape while its abstract method remains unimplemented.

12. Special Methods: __str__() and __repr__()

Special methods allow classes to define behavior for built-in operations.

  • __str__() provides a user-friendly string representation.

  • __repr__() provides a representation intended to be useful for debugging and development.

Example

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

    def __str__(self):
        return f"{self.name}, age {self.age}"

student = Student("Rahul", 20)
print(student)

Output

Rahul, age 20

When print() receives an object, Python uses its string representation.

13. Practical Example: Employee Management

The following example combines classes, constructors, methods, and object creation.

class Employee:
    company = "Param Technologies"

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

    def display_details(self):
        print(f"Name: {self.name}")
        print(f"Employee ID: {self.employee_id}")
        print(f"Salary: {self.salary}")
        print(f"Company: {self.company}")

    def increase_salary(self, amount):
        if amount > 0:
            self.salary += amount

employee = Employee("Amit", 101, 30000)

employee.increase_salary(5000)
employee.display_details()

Output

Name: Amit
Employee ID: 101
Salary: 35000
Company: Param Technologies

This example demonstrates how an object can store employee information and perform operations on that information.

14. Advantages of OOP in Python

  • Code Reusability: Inheritance helps reuse existing functionality.

  • Maintainability: Organizing related behavior into classes can make code easier to manage.

  • Encapsulation: Properties and conventions help control access to internal data.

  • Extensibility: Classes can be extended to support new requirements.

  • Abstraction: Abstract classes can define common interfaces.

  • Polymorphism: Different objects can be used through a common interface.

OOP is useful when an application contains related entities with data and behavior. For smaller scripts, simple functions may be more appropriate.

15. Common OOP Mistakes to Avoid

  1. Forgetting self in an instance method.

  2. Confusing class variables with instance variables.

  3. Forgetting to initialize attributes in __init__().

  4. Using inheritance when simple composition would be clearer.

  5. Assuming an underscore-prefixed attribute is strictly private.

  6. Using mutable class variables unintentionally when each object needs its own list or dictionary.

  7. Overcomplicating a small program with unnecessary classes.

16. Best Practices for Python OOP

  • Use descriptive class and method names.

  • Follow Python naming conventions: PascalCase for class names and snake_case for methods and variables.

  • Keep each class focused on a clear responsibility.

  • Use properties when controlled attribute access is needed.

  • Prefer composition over complicated inheritance hierarchies when appropriate.

  • Write docstrings for classes and important methods.

  • Validate input before changing important object state.

  • Add tests for important class behavior.

17. Python OOP Practice Questions

  1. Create a Student class with name, roll number, and marks.

  2. Create two objects from the same class with different data.

  3. Create a Car class using __init__() and a method to display details.

  4. Demonstrate single inheritance using Animal and Dog.

  5. Demonstrate method overriding using Vehicle and Car.

  6. Create a class method and a static method.

  7. Build a BankAccount class with deposit and withdrawal methods.

  8. Create an abstract Shape class with an area() method.

  9. Demonstrate polymorphism using Dog and Cat classes.

  10. Override __str__() to display an object's information.

18. Python OOP Interview Questions and Answers

Q1. What is OOP in Python?

OOP is a programming approach that organizes code using classes and objects.

Q2. What is a class?

A class is a blueprint that defines attributes and methods for its objects.

Q3. What is an object?

An object is an instance of a class.

Q4. What is self in Python?

self refers to the current instance and is used to access its attributes and methods.

Q5. What is __init__()?

It is an initializer method that runs when an object is created.

Q6. What is inheritance?

Inheritance allows a class to reuse and extend behavior from another class.

Q7. What is polymorphism?

Polymorphism allows the same operation or method name to work with different types of objects.

Q8. What is encapsulation?

Encapsulation organizes data and behavior together and supports controlled access to internal state.

Q9. What is abstraction?

Abstraction exposes essential behavior while hiding unnecessary implementation details.

Q10. What is method overriding?

Method overriding occurs when a child class provides its own implementation of an inherited method.

Q11. What is the difference between a class variable and an instance variable?

A class variable is associated with the class and commonly shared across instances. An instance variable belongs to a particular object.

Q12. What is the purpose of super()?

super() provides access to methods in the next class in the method resolution order, commonly used to call parent-class behavior.

Conclusion

Object-Oriented Programming is an important part of Python development. Understanding classes, objects, constructors, inheritance, encapsulation, polymorphism, and abstraction helps developers build organized and reusable applications.

Practice each example, modify the code, and create small projects to strengthen your Python OOP skills.

←
Post 16 of 20
→