⬅ Previous Next ➡

Object-Oriented Programming

OOP Basics: Class and Object
  • Class is a blueprint/template.
  • Object is an instance of a class.
  • Class defines data (variables) and behavior (methods).
class Student:
    pass

s1 = Student()
s2 = Student()
print(s1, s2)
Constructor (__init__)
  • Constructor is a special method called automatically when object is created.
  • In Python, constructor is __init__.
  • self refers to the current object.
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

s = Student("Sourav", 25)
print(s.name, s.age)
Variables in Class (Instance, Class, Local)
  • Instance variable: belongs to object (self.var)
  • Class variable: shared by all objects (ClassName.var)
  • Local variable: inside a method only
class Demo:
    company = "WebTechIO"   # class variable

    def __init__(self, name):
        self.name = name    # instance variable

    def show(self):
        x = 10              # local variable
        print(self.name, Demo.company, x)

d1 = Demo("A")
d2 = Demo("B")
Demo.company = "QuiteXams"
d1.show()
d2.show()
Methods (Instance, Classmethod, Staticmethod)
  • Instance method: uses self and works with object data.
  • @classmethod: uses cls and works with class data.
  • @staticmethod: no self/cls, utility method.
class Calc:
    brand = "SimpleCalc"

    def add(self, a, b):          # instance method
        return a + b

    @classmethod
    def info(cls):                # class method
        return cls.brand

    @staticmethod
    def is_even(n):               # static method
        return n % 2 == 0

c = Calc()
print(c.add(10, 20))
print(Calc.info())
print(Calc.is_even(6))
Inheritance (Single Inheritance)
  • Inheritance allows a child class to use features of parent class.
  • Helps code reuse and extends functionality.
class Animal:
    def speak(self):
        print("Animal sound")

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

d = Dog()
d.speak()
d.bark()
Polymorphism (Method Overriding)
  • Polymorphism = same method name, different behavior.
  • Method overriding: child class redefines parent method.
class Animal:
    def speak(self):
        print("Animal speaks")

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

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

animals = [Cat(), Dog()]
for a in animals:
    a.speak()
Encapsulation (Data Hiding)
  • Encapsulation = wrapping data and methods together.
  • Use access modifiers by naming convention:
  • public: name
  • protected: _name
  • private: __name (name mangling)
class Account:
    def __init__(self, balance):
        self.__balance = balance   # private

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

    def get_balance(self):
        return self.__balance

acc = Account(1000)
acc.deposit(500)
print(acc.get_balance())
Abstraction (Hiding Implementation)
  • Abstraction = show only required features, hide internal details.
  • In Python, can be done using abc module (abstract base class).
from abc import ABC, abstractmethod

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

class Square(Shape):
    def __init__(self, side):
        self.side = side

    def area(self):
        return self.side * self.side

s = Square(5)
print(s.area())
super() (Calling Parent Class)
  • super() is used to call parent class constructor/method.
  • Commonly used in inheritance to reuse parent initialization.
class Person:
    def __init__(self, name):
        self.name = name

class Student(Person):
    def __init__(self, name, roll):
        super().__init__(name)
        self.roll = roll

s = Student("Sourav", 101)
print(s.name, s.roll)
Dunder Methods (Magic Methods)
  • Dunder methods start and end with double underscore.
  • Used to customize class behavior.
  • Common: __str__, __len__, __add__, __repr__
class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

    def __str__(self):
        return f"Book: {self.title}"

    def __len__(self):
        return self.pages

b = Book("Python Notes", 120)
print(b)           # calls __str__
print(len(b))      # calls __len__
⬅ Previous Next ➡