Python OOP Complete

Object-Oriented Programming

Master all four pillars of OOP — Encapsulation, Inheritance, Polymorphism, and Abstraction with practical examples.

Python 3 4 Pillars 8 Topics Interview Key
01

Introduction to OOP

OOP is a programming style that organizes code using objects and classes. It models real-world things using programming structures — used in software development, game development, web frameworks, and system design.

The Four Pillars of OOP
Encapsulation

Protect Data

Bundling data and methods together, restricting direct access to internal state.

ATM hides bank database — interact only through buttons
Inheritance

Reuse Code

A child class acquires properties and methods from a parent class.

Child inherits traits from parent — eye color, height
Polymorphism

Many Behaviors

One interface, many forms. Same method name behaves differently depending on the object.

"Drive" means different things for a car vs a bike
Abstraction

Hide Complexity

Shows only essential features while hiding implementation details.

You press the accelerator — engine details are hidden
02

Classes & Objects

A class is a blueprint. An object is a real-world entity created from that blueprint.

Python — Complete Class Example
class Student:
    def __init__(self, name, age, marks):
        self.name  = name
        self.age   = age
        self.marks = marks

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

    def is_passed(self):
        return self.marks >= 40

s1 = Student("Alice", 20, 85)
s2 = Student("Bob", 22, 35)

s1.display()                     # Name: Alice, Age: 20
print("Passed:", s1.is_passed()) # Passed: True
print("Passed:", s2.is_passed()) # Passed: False
Class
Blueprint — defines structure and behavior.
Object (Instance)
Concrete entity built from the class.
Attribute
Data stored in an object using self.attr = value.
Method
Function inside a class. First param is always self.
03

Instance, Class & Static Methods

Python classes support three types of methods. Quick memory trick: I C S — Instance / Class / Static.

Instance Method
def method(self):
Works with object data. Most common.
Class Method
@classmethod + cls
Works with class-level data.
Static Method
@staticmethod
Utility — no self or cls.
Python — All Three Method Types
class Student:
    school_name = "ABC School"   # Class variable

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

    def display(self):           # Instance method
        print(self.name, self.marks)

    @classmethod
    def get_school(cls):         # Class method
        return cls.school_name

    @staticmethod
    def grade(marks):           # Static method (utility)
        return "A" if marks >= 90 else "B"

Quick Memory Trick — I C S

I
Instance
self → object
C
Class
cls → class
S
Static
no reference
04

Encapsulation

Encapsulation means bundling data and methods together and restricting direct access.

Access TypeConventionExampleAccessible From
PublicNo prefixself.nameAnywhere
ProtectedSingle underscoreself._nameInternal use (convention)
PrivateDouble underscoreself.__nameClass only (name mangling)
Python — Encapsulation (Bank Account)
class BankAccount:
    def __init__(self, balance):
        self.__balance = balance   # Private variable

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

    def withdraw(self, amount):
        if amount <= self.__balance:
            self.__balance -= amount

    def get_balance(self):     # Getter method
        return self.__balance
05

Inheritance

Inheritance allows a child class to reuse properties and methods from a parent class. Use super() to call parent methods.

Types of Inheritance

Single

One parent → One child

A → B

Multiple

Child inherits from multiple parents

A, B → C

Multilevel

An inheritance chain

A → B → C

Hierarchical

Multiple children from one parent

A → B, A → C
Python — Method Overriding + super()
class Animal:
    def speak(self):
        print("Animal makes a sound")

class Dog(Animal):
    def speak(self):          # Override parent method
        super().speak()      # Call parent first
        print("Dog barks")
06

Polymorphism

Polymorphism = one interface, many behaviors. Achieved through method overriding, operator overloading, and duck typing.

Python — Polymorphism Examples
# Method overriding polymorphism
class Dog(Animal):
    def speak(self): print("Dog barks")

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

for a in [Dog(), Cat()]:
    a.speak()      # Same call, different behavior

# Operator overloading
print(5 + 3)           # 8 (addition)
print("Hi " + "There") # string concat
07

Abstraction

Abstraction means hiding complex implementation details using the abc module with Abstract Classes.

Python — Abstract Classes (ABC)
from abc import ABC, abstractmethod

class Shape(ABC):              # Abstract class
    @abstractmethod
    def area(self): pass       # Must be implemented

class Rectangle(Shape):
    def __init__(self, w, h):
        self.w = w; self.h = h

    def area(self):
        return self.w * self.h

r = Rectangle(4, 5)
print(r.area())                 # 20
08

Magic Methods (Dunder)

Magic methods start and end with double underscores. They let objects behave like built-in types.

__init__
Constructor
__str__
User string representation
__repr__
Developer representation
__len__
Length of object
__add__
Addition operator
__eq__
Equality comparison
__getitem__
Index access
__call__
Callable object
__iter__
Iterator protocol
__next__
Next value
__del__
Destructor
__enter__/__exit__
Context manager

Quick Quiz

1. __init__ is a…
2. MRO determines…
3. @classmethod receives…
4. @staticmethod vs @classmethod — static has…
5. Encapsulation in Python often uses…