Introduction
Object Oriented Programming (OOP) का सबसे पहला और महत्वपूर्ण concept है Class
Class एक blueprint (नक्शा) या template होता है, जिसकी मदद से हम objects बनाते हैं।
यह data (variables) और functions (methods) को एक साथ organize करता है।
Class क्या होती है
Class एक user-defined data structure है, जिसमें हम variables और methods को define करते हैं।
सरल शब्दों में:
Class = properties (data) + methods (functions)
Real-life समझ
जैसे:
- Class → Car
- Properties → color, speed
- Methods → start(), stop()
इसी तरह programming में भी class बनाई जाती है।
Class का basic syntax
class ClassName:
# variables
# methods
Example (Basic Class)
class Student:
name = "Rahul"
age = 20
Class का object बनाना
s1 = Student()
print(s1.name)
Output
Rahul
init Method (Constructor)
Definition
__init__() एक special method होता है, जो object create होते समय automatically call होता है।
Example
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
s1 = Student("Amit", 21)
print(s1.name)
print(s1.age)
self keyword
- self object को represent करता है
- हर method में पहला parameter होता है
- इसकी मदद से हम object की properties access करते हैं
Instance Variables
जो variables self के साथ define होते हैं, उन्हें instance variables कहते हैं।
class Student:
def __init__(self, name):
self.name = name
Class Variables
जो variables class के अंदर सीधे define होते हैं, उन्हें class variables कहते हैं।
class Student:
school = "ABC School"
Methods in Class
Class के अंदर define किए गए functions को methods कहते हैं।
class Student:
def greet(self):
print("Hello Student")
Example (Class + Method)
class Student:
def __init__(self, name):
self.name = name def show(self):
print("Name:", self.name)
s1 = Student("Rahul")
s1.show()
Multiple Objects
s1 = Student("Rahul")
s2 = Student("Amit")print(s1.name)
print(s2.name)
Real-life Example: Car class
class Car:
def __init__(self, brand):
self.brand = brand def start(self):
print(self.brand, "started")
c1 = Car("Toyota")
c1.start()
Real-life Example: Bank account
class Account:
def __init__(self, balance):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print("Balance:", self.balance)
acc = Account(1000)
acc.deposit(500)
Important Points
- Class blueprint होता है
- Object instance होता है
- init constructor होता है
- self object को refer करता है
Common mistakes
- self parameter भूल जाना
- init को गलत लिखना
- object create किए बिना method call करना
Mini Program
class Person:
def __init__(self, name):
self.name = name
def greet(self):
print("Hello", self.name)
p1 = Person("Amit")
p1.greet()
Summary
Class OOP का foundation है।
इसकी मदद से हम structured और reusable code बना सकते हैं।