Python OOP Concepts – Class, Inheritance, Encapsulation & Polymorphism (Simple Notes) 🐍

Python OOP Concepts – Simple Short Notes
In this lesson, we learn Object Oriented Programming (OOP) concepts in simple English.


Simple diagram explaining Python OOP concepts including class, inheritance, polymorphism and encapsulation
Educational infographic showing Python OOP concepts like Class, Constructor, Inheritance, Polymorphism and Encapsulation in simple way.


🔹 1. Class & Object

A class is a blueprint. An object is created from a class.

class MyCar:
    wheels = 4   # class attribute

    def display_info(self):
        print(f"This car runs on {self.wheels} wheels")

car_1 = MyCar()
car_1.display_info()

🔹 2. Constructor (__init__)

__init__ is used to initialize values when creating an object.

class MyCar:
    wheels = 4

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

    def display_info(self):
        print(f"{self.color} {self.brand} drives on {self.wheels} wheels")

car_1 = MyCar("BMW", "Red")
car_1.display_info()

🔹 3. Rectangle Example

Demonstrating methods inside methods.

class Rectangle:

    def __init__(self, length, width):
        self.length = length
        self.width = width

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

    def perimeter(self):
        return 2 * (self.length + self.width)

    def describe(self):
        print(f"Area is {self.area()} and Perimeter is {self.perimeter()}")

rectangle = Rectangle(10, 5)
rectangle.describe()

🔹 4. Inheritance

Inheritance allows a child class to use parent class properties.

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def speak(self):
        print("Dog barks")

dog_1 = Dog()
dog_1.speak()

🔹 Method Overriding

Overriding means a child class changes the method of the parent class.

The method name must be the same in both classes.

✅ Example 1: Basic Overriding

class Animal:   # Parent class
    age = 0

    def speak(self):
        print("Animal speak")

class Dog(Animal):   # Child class
    def speak(self):   # Overriding parent method
        print("Dog bark")

dog_1 = Dog()
print(dog_1.age)   # Inherited attribute
dog_1.speak()      # Calls overridden method

✔ The Dog class overrides the speak() method of Animal.


⚠ Constructor Inheritance Problem

If the parent class has a constructor, the child must pass required arguments.

class Animal:
    def __init__(self, color):
        self.color = color

class Dog(Animal):
    def speak(self):
        print("Dog bark")

# dog_1 = Dog()  ❌ Error (missing color argument)

✔ Fix using super() to call parent constructor.

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

class Dog(Animal):
    def __init__(self, name, color):
        super().__init__(name)  # Call parent constructor
        self.color = color

    def speak(self):
        print(f"{self.name} barks")

dog_1 = Dog("Buddy", "Brown")
print(dog_1.name)
print(dog_1.color)

✅ Real World Example (Employee & Manager)

class Employee:

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

    def display_info(self):
        print(f"Name: {self.name}, Salary: {self.salary}", end="")

class Manager(Employee):

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

    def display_info(self):  # Overriding method
        super().display_info()
        print(f", Department: {self.department}")

manager_1 = Manager("Sherul", "2000.00", "Academic")
manager_1.display_info()

✔ Manager class overrides display_info() and adds department.


🔹 Method Overloading

Overloading means using the same method name but with different parameters.

⚠ Python does not support traditional overloading like Java. We simulate it using default arguments.

✅ Example: Simulated Overloading

class Animal:
    age = 0

    def speak(self):
        print("Animal speak")

class Dog(Animal):

    def speak(self, bark=None):   # Overloading style
        if bark is None:
            print("Dog barks loudly!")
        else:
            print(f"Dog barks: {bark}")

dog_1 = Dog()
print(dog_1.age)

dog_1.speak()              # Without argument
dog_1.speak("woof woof")   # With argument

✔ Same method name speak() works in two different ways.


🔹 6. Polymorphism

Same method name behaves differently in different classes.

class Dog:
    def speak(self):
        print("Dog barks")

class Cat:
    def speak(self):
        print("Cat meows")

🔹 7. Encapsulation

Encapsulation means hiding data using private attributes.

class Car:
    def __init__(self, brand):
        self.__brand = brand   # private

    def get_brand(self):
        return self.__brand

car = Car("Toyota")
print(car.get_brand())

🔹 8. BankAccount Example (Encapsulation)

class BankAccount:

    def __init__(self, account_number, owner_name):
        self.__account_number = account_number
        self.__owner_name = owner_name
        self.__balance = 0.0

    def __valid_amount(self, amount):
        return amount > 0

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

    def withdraw(self, amount):
        if self.__valid_amount(amount) and self.__balance >= amount:
            self.__balance -= amount

    def get_balance(self):
        return self.__balance

account = BankAccount("213", "Sherul")
account.deposit(1000)
print(account.get_balance())

🎯 These OOP concepts are very important for real-world Python projects.

📚 Related Articles

Article No Article Title & Link
1 🐍 Getting Started with Python for Data Science – Fundamentals Guide 🚀
2 🐍 Python Collections (Arrays) Simplified: List, Tuple, Set, & Dictionary 🐍
3 🐍 Understanding Python Lists in Simple Way 📋
4 🐍 Understanding Python Tuples in Simple Way 📦
5 🐍 Understanding Python Sets in Simple Way 🎴
6 🐍 Understanding Python Range & Dictionaries 📘
7 🐍Python Operators Guide: Arithmetic, Logical, & Precedence Explained 🐍
8 🐍 Python Control Statements Complete Guide 🔄
9 🐍 Python Functions Explained in Simple Way ⚙️
10 🐍 Python Map, Filter, Lambda & Modules – Simple Notes
11 🐍 Python OOP Concepts – Simple Short Notes
12 🐍  NumPy, Pandas & Web Scraping – Simple Python Notes📊

Post a Comment

Previous Post Next Post