Python – Class & Objects
🔷 Python – Class & Objects (Easy Hinglish Notes)
🔸 Class kya hoti hai?
Class ek design hoti hai — blueprint jiske base par hum objects banate hain.
Example: Car ek class hai — lekin actual car (Maruti, Honda) object hai.
🔸 Object kya hota hai?
Object class ka real example hota hai — jiske paas properties (data) aur functions (methods) hote hain.
🔸 Syntax of Class and Object:
class ClassName:
def __init__(self):
# constructor
print("Object bana")
# object create karna
obj = ClassName()
🔸 Example 1 – Simple Class:
class Student:
def __init__(self):
print("Student object created")
s1 = Student()
🟢 Output:
Student object created
🔸 Example 2 – Class with Attributes:
class Student:
def __init__(self, name, marks):
self.name = name
self.marks = marks
def show(self):
print("Name:", self.name)
print("Marks:", self.marks)
s1 = Student("Navghan", 90)
s1.show()
🟢 Output:
Name: Navghan
Marks: 90
🔸 __init__()
kya hota hai?
-
Ye ek special function (constructor) hai jo object banate hi automatic call hota hai.
-
self
ka matlab hota hai — current object.
🟨 Practice Exercises with Solutions
✅ Exercise 1:
Ek class Car
banao jisme brand aur price ho, aur ek method ho show()
details print karne ke लिए।
class Car:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def show(self):
print("Brand:", self.brand)
print("Price:", self.price)
c1 = Car("Honda", 800000)
c1.show()
✅ Exercise 2:
Ek class Circle
banao jo radius le aur area return kare.
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
c = Circle(5)
print("Area of circle:", c.area())
✅ Exercise 3:
Ek class Person
banao jo naam aur umar rakhe aur ek method greet()
ho jo Hello Navghan, your age is 21
jaise print kare.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello {self.name}, your age is {self.age}")
p = Person("Navghan", 21)
p.greet()
अगर तुम चाहो तो मैं aur bhi practice exercises, MCQs, ya ek mini project (like Student Management System) bhi bana सकता हूँ। बताओ कैसे आगे बढ़ना है?
Comments
Post a Comment