πΉ What is a Class?
- A class is a template or design to make things (objects).
- It tells Python what the object has (variables) and what it can do (functions).
β Example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
This class is like a student form. It has:
name
age
πΉ What is an Object?
- An object is something real made from the class.
- We can make many objects from one class.
β Example:
s1 = Student("Arun", 18)
print(s1.name) # Output: Arun
β‘οΈ s1
is an object of the class Student
.
πΉ __init__()
Method
- This is a special function in the class.
- It runs automatically when you make an object.
- It gives values to the object.
β Example:
class Car:
def __init__(self, brand):
self.brand = brand
c1 = Car("Toyota")
print(c1.brand) # Output: Toyota
πΉ What is self
?
self
means this object.- It is used to store data inside the object.
β Example:
class Example:
def show(self):
print("Hello from", self)
obj = Example()
obj.show()
π§ Real-Life Example
Letβs say we want to make details of books.
β Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
b1 = Book("Python Basics", "Ravi")
print(b1.title) # Python Basics
print(b1.author) # Ravi
β Benefits of Using Class and Object
Why we use OOP? | Simple Explanation |
---|---|
Reuse Code | Use the same class to make many objects |
Clean Code | Easy to read and update |
Better Structure | Keep data and actions together |
π Practice Questions
Q1. Create a class Employee
with name and salary. Show details.
β Answer:
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def show(self):
print("Name:", self.name)
print("Salary:", self.salary)
e1 = Employee("Meena", 25000)
e1.show()
π§Ύ Summary Table
Word | Meaning |
---|---|
Class | Blueprint for making objects |
Object | Real item created from class |
__init__() | Gives values when object is created |
self | Refers to the current object |
π Next Topic:
β‘οΈ __init__()
in Python – Constructor Made Simple (Coming up next)
Leave a Reply