Chapter 9: OOP in Python

Chapter 9: Object-Oriented Programming in Python

Class, Object, __init__, Inheritance, Polymorphism, Encapsulation, Abstraction, super(), Method Overriding & Operator Overloading – Sab kuch step-by-step in Hinglish!

1. Class & Object

Class: Ek blueprint ya template hoti hai. Jaise Car ka design.

Object: Real cheez jo class ke base par banai jaati hai. Jaise "BMW" aur "Audi" car objects ho sakti hain.

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

car1 = Car("BMW")
print(car1.brand)
BMW

2. __init__ Method

Yeh ek special constructor method hota hai jo object banate waqt automatically call hota hai. Initialization ke liye use hota hai.

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

s1 = Student("Ravi", 20)
print(s1.name, s1.age)
Ravi 20

3. Instance vs Class Variables

  • Instance Variable: Har object ke liye alag value.
  • Class Variable: Sab objects ke liye common hoti hai.
class Dog:
 species = "Canine" # Class Variable
 def __init__(self, name):
 self.name = name # Instance Variable

d1 = Dog("Bruno")
print(d1.name, d1.species)
Bruno Canine

4. Inheritance

Ek class doosri class ke properties aur methods le sakti hai.

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

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

d = Dog()
d.speak()
d.bark()
Animal speaking
Dog barking

5. Polymorphism

Same method name, lekin different behavior.

class Bird:
 def fly(self):
 print("Bird flying")

class Airplane:
 def fly(self):
 print("Airplane flying")

def flight_test(thing):
 thing.fly()

flight_test(Bird())
flight_test(Airplane())
Bird flying
Airplane flying

6. Encapsulation

Data ko protect karna by restricting access using _ (protected) or __ (private).

class Account:
 def __init__(self):
 self.__balance = 0

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

 def get_balance(self):
 return self.__balance

acc = Account()
acc.deposit(500)
print(acc.get_balance())
500

7. Abstraction

Important details ko dikhana aur complex logic ko hide karna.

from abc import ABC, abstractmethod

class Vehicle(ABC):
 @abstractmethod
 def start(self):
 pass

class Bike(Vehicle):
 def start(self):
 print("Bike started")

b = Bike()
b.start()
Bike started

8. super() and Method Overriding

Child class parent method ko override kar sakti hai. super() se parent ka method bhi call kar sakte hain.

class Parent:
 def show(self):
 print("Parent show")

class Child(Parent):
 def show(self):
 super().show()
 print("Child show")

c = Child()
c.show()
Parent show
Child show

9. Operator Overloading

Operators (+, *, etc.) ko custom objects ke liye define karna.

class Book:
 def __init__(self, pages):
 self.pages = pages

 def __add__(self, other):
 return self.pages + other.pages

b1 = Book(100)
b2 = Book(150)
print(b1 + b2)
250