Chapter 11Python Tutorial~1 min read
OOP — Classes & Objects
Object Oriented Programming
OOP म्हणजे Object Oriented Programming. Code ला real-world objects च्या रूपात organize करतो. Class म्हणजे blueprint आणि Object म्हणजे त्या blueprint चा एक actual instance.
Marathi Analogy
Class म्हणजे Idli maker चा साचा. एकाच साच्यातून 10 Idli बनवता येतात. प्रत्येक Idli एक object! Car ही एक class — प्रत्येक गाडी (Maruti, Honda) एक object. सगळ्यात wheels, engine, doors असतात — पण values वेगळ्या.
Class बनवणे
Class definition
python
# Class define करणे
class Student:
# Class attribute (सगळ्या objects साठी same)
school = "ABC School"
# __init__ = constructor — object बनवताना call होतो
def __init__(self, name, marks):
self.name = name # instance attribute
self.marks = marks
# Method — class मधला function
def greet(self):
print(f"नमस्कार, मी {self.name}!")
def result(self):
if self.marks >= 40:
print(f"{self.name} — Pass ✅")
else:
print(f"{self.name} — Fail ❌")Objects बनवणे
Creating and using objects
python
# Object (instance) बनवणे
s1 = Student("Rahul", 85)
s2 = Student("Priya", 35)
# Methods call करणे
s1.greet() # नमस्कार, मी Rahul!
s2.greet() # नमस्कार, मी Priya!
s1.result() # Rahul — Pass ✅
s2.result() # Priya — Fail ❌
# Attributes access करणे
print(s1.name) # Rahul
print(s1.marks) # 85
print(s1.school) # ABC School — class attribute
# Attribute modify करणे
s1.marks = 90
print(s1.marks) # 90Inheritance — Parent पासून inherit करणे
Inheritance example
python
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
print(f"{self.name} बोलतो...")
# Dog inherits from Animal
class Dog(Animal):
def speak(self): # Override करतो!
print(f"{self.name} भुंकतो: Woof! Woof!")
class Cat(Animal):
def speak(self):
print(f"{self.name} म्हणतो: Meow! Meow!")
d = Dog("Bruno")
c = Cat("Whiskers")
d.speak() # Bruno भुंकतो: Woof! Woof!
c.speak() # Whiskers म्हणतो: Meow! Meow!
# Parent method access
print(d.name) # Bruno — Animal कडून inherit केले✅ Key Points — लक्षात ठेवा
- ▸class ClassName: — class define करतो
- ▸__init__(self, ...) — constructor, object बनवताना run होतो
- ▸self — current object ला refer करतो
- ▸object = ClassName(args) — object बनवणे
- ▸class Child(Parent): — inheritance
0/12 chapters पूर्ण