πΉ What is self in Python?
selfmeans this object.- It helps Python know which object we are talking about.
- It is used inside class functions to access the objectβs data and functions.
π Important Points:
selfis not a keyword. You can name it anything (but usingselfis the rule).- It is sent automatically when you call a function using an object.
πΉ Example 1: Using self to store data
class Student:
def __init__(self, name, age):
self.name = name # save name
self.age = age # save age
def show(self):
print("Name:", self.name)
print("Age:", self.age)
s1 = Student("Arun", 18)
s1.show()
β Output:
Name: Arun
Age: 18
πΉ How self works:
Letβs understand:
self.name = nameβ store the value in the object.self.age = ageβ same for age.- Later, inside the
show()function, we again useself.nameto get the data back.
πΉ Example 2: Use self in multiple objects
class Car:
def __init__(self, brand):
self.brand = brand
def start(self):
print(self.brand, "is starting...")
c1 = Car("Toyota")
c2 = Car("BMW")
c1.start() # Toyota is starting...
c2.start() # BMW is starting...
π Here, self.brand is different for each object.
πΉ Example 3: Change values using self
class Employee:
def __init__(self, name, salary):
self.name = name
self.salary = salary
def change_salary(self, new_salary):
self.salary = new_salary
def show(self):
print("Name:", self.name)
print("Salary:", self.salary)
e1 = Employee("Ravi", 30000)
e1.change_salary(40000)
e1.show()
β Output:
Name: Ravi
Salary: 40000
π Practice Questions with Answers
β Q1: Create a class Laptop with brand and price. Use self to store and print data.
β Answer:
class Laptop:
def __init__(self, brand, price):
self.brand = brand
self.price = price
def show(self):
print("Brand:", self.brand)
print("Price:", self.price)
l1 = Laptop("HP", 55000)
l1.show()
β Q2: Create a class Circle with radius. Use a method to calculate area. (Area = 3.14 Γ radius Γ radius)
β Answer:
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
c = Circle(5)
print("Area:", c.area())
π§Ύ Summary Table
| Term | Meaning |
|---|---|
self | Refers to current object inside a class |
| Use | To access variables and methods in object |
π£ Next:
β‘οΈ βEncapsulation in Python | Easy OOP Explanation for Beginnersβ
