Python OOP Introduction
In this page:
OOP क्या है?
Object-Oriented Programming code को standalone functions के बीच data पास करने की बजाय objects के इर्द-गिर्द organize करता है जो data और behavior को साथ बांधते हैं — यह real-world चीज़ों के काम करने के तरीके को mirror करता है (एक car के color जैसी properties भी होती हैं और drive() जैसे actions भी) और programs बढ़ने पर related logic को एक जगह रखता है।
उदाहरण: What is OOP?
class Car:
color = "red" # attribute shared by every instance
def drive(self):
print("Driving")
Car().drive() # create an object and call its method
Objects और Classes
Class एक blueprint है — यह define करती है कि उस type के हर object के पास कौन-से attributes और methods होंगे — जबकि object उस blueprint से बनी एक concrete instance है, जिसकी अपनी actual values होती हैं (दो Car objects class definition share करते हैं पर उनके colors अलग होते हैं)।
उदाहरण: Objects and Classes
class Car:
def __init__(self, color):
self.color = color # each instance stores its own color
car1 = Car("red")
car2 = Car("blue")
print(car1.color, car2.color) # same class, different attribute values
Encapsulation
Encapsulation किसी object के internal data को उस पर काम करने वाले methods के साथ बांधे रखता है और बाहर से direct access सीमित करता है — Python में यह enforced rule नहीं बल्कि एक convention है, जिसे attribute names के आगे underscore या double underscore लगाकर signal किया जाता है।
उदाहरण: Encapsulation
class Account:
def __init__(self, balance):
self._balance = balance # underscore signals "internal use"
print(Account(100)._balance)
Abstraction
Abstraction का मतलब है सिर्फ वही expose करना जो आपकी class के user को जानना चाहिए (जैसे एक .drive() method) और उसके पीछे की गड़बड़ implementation details (engine RPM calculations, gear ratios) को छिपाना — इससे आप class को इस्तेमाल करने वाले code को तोड़े बिना बाद में internals बदल सकते हैं।
उदाहरण: Abstraction
class Car:
def drive(self):
print("Engine details are hidden from the caller") # implementation is hidden behind the method
Car().drive()
OOP के फ़ायदे
चूँकि classes को copy-paste करने की बजाय पूरे codebase में extend और reuse किया जा सकता है, OOP ज़्यादा modular code बनाता है — किसी base class में बग fix करना या feature जोड़ना अपने-आप उससे inherit करने वाली हर class को फ़ायदा पहुँचाता है।
उदाहरण: Benefits of OOP
class Animal:
def eat(self):
print("Eating")
class Dog(Animal):
pass
Dog().eat() # inherited automatically
Chapter Quiz — Complete all 11 topics to unlock
0/11 topics done
Complete these topics first: