🔹 What is self
in Python?
self
means 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:
self
is not a keyword. You can name it anything (but usingself
is 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.name
to 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”
Leave a Reply