Python OOPS

Python OOP – Fundamentals

Object-Oriented Programming (OOP) is a programming style organized around objects instead of functions.
It helps structure code that is scalable, reusable, and modular.


Four Pillars of OOP

PillarMeaningExample
EncapsulationHiding internal detailsPrivate variables
AbstractionShowing only necessary featuresInterfaces-like behavior
InheritanceAcquiring properties from parent classParent → Child
PolymorphismSame function name, different behaviorMethod overriding

Basic Terminology

TermMeaning
ClassBlueprint/template for an object
ObjectInstance created from a class
MethodA function inside a class
AttributeVariables in a class (properties)
ConstructorInitializes object values (__init__())
class Person:
    def __init__(self, name, age):
        self.name = name    # Instance attribute
        self.age = age

    def greet(self):
        print(f"Hello, my name is {self.name} and I am {self.age} years old.")

p1 = Person("Amit", 25)
p1.greet()

Description

  • Person is a class (blueprint).
  • p1 is an object/instance of the class.
  • __init__ is a constructor that initializes object attributes when created.
  • self refers to the current object.
  • greet() is an instance method, accessible using the object.

class Employee:
    company = "Google"  # Class variable (shared by all objects)

    def __init__(self, name):
        self.name = name  # Instance variable (unique to each object)

e1 = Employee("Sam")
e2 = Employee("Riya")
print(e1.company, e2.company)
print(e1.name, e2.name)

Description

  • company belongs to the class, so every Employee object uses “Google”.
  • name is an instance variable — each object has a different value.
  • Helps differentiate data shared across objects and unique to each.

Encapsulation refers to the concept of bundling data and methods that operate on that data into a single unit, i.e., a class. It prevents direct access to data from outside the class and promotes data hiding.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # Private variable

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

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

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

Description

  • The variable __balance is private and cannot be accessed directly using object.
  • Encapsulation protects data from accidental modification.
  • We control access through getter & setter functions.

from abc import ABC, abstractmethod

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

class Circle(Shape):
    def __init__(self, r):
        self.r = r

    def area(self):
        return 3.14 * self.r * self.r

c = Circle(5)
print(c.area())

Description

  • Shape is an abstract class — cannot be instantiated.
  • Contains an abstract method that forces subclasses to implement it.
  • The Circle must provide its own area method → ensuring a standard structure.

class Sample:
    def __init__(self):
        print("Constructor executed")

    def __del__(self):
        print("Destructor executed")

obj = Sample()
del obj

Description

  • __init__ runs automatically when the object is created.
  • __del__ runs when the object is destroyed or the program ends.
  • Used for resource management (like closing files, DB connections, etc.)

  1. Class Method
  • In Python, a class method is a type of method that is bound to the class itself rather than to instances of the class.
  • It can access and modify class-level attributes and perform actions related to the class as a whole.
  • Class methods are defined using the @classmethod decorator and take the class itself as the first parameter, conventionally named cls.
  • This makes them different from instance methods, which take the instance itself (self) as the first parameter.
  1. Static Method
  • A static method is a method that is defined within a class but is not bound to the class instance or class-level attributes.
  • It doesn’t receive any implicit reference to the class or its instances as parameters. Static methods are defined using the @staticmethod decorator.
  • Static methods are often used to create utility functions that are logically related to the class but don’t require access to instance-specific or class-level data.
class Student:
    school = "DAV School"

    @staticmethod
    def welcome():
        print("Welcome to the School!")  # No object needed

    @classmethod
    def get_school_name(cls):
        return cls.school

Student.welcome()
print(Student.get_school_name())

Description

  • @staticmethod → Does not access class or object data. Used as helper logic.
  • @classmethod → Access class variables using cls.

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

    def details(self):
        print(f"{self.brand} {self.model} costs ₹{self.price}")

c1 = Car("Toyota", "Fortuner", 3500000)
c1.details()

Description

  • Represents real-world entities as Python objects.
  • Helps in designing software similar to real systems.

Leave a Comment