Yes! The word self in Python is a reference to the current instance of the class. It allows you to access instance attributes and methods within the class.
- Access Instance Variables: It helps differentiate between instance variables and local variables inside a method.
- Call Other Methods: It allows one method to call another method within the same class.
- Maintain Object State: It ensures that data associated with an instance persists across method calls.
- When a method is called on an instance,
self automatically refers to that specific instance.
- Without
self, Python wouldn’t know which instance’s attributes or methods you’re referring to.
def __init__(self, brand, model):
self.brand = brand # Instance variable
self.model = model # Instance variable
print(f"Car Brand: {self.brand}, Model: {self.model}")
def change_model(self, new_model):
self.model = new_model # Modifies instance attribute
self.display_info() # Calling another method using self
my_car = Car("Toyota", "Camry")
my_car.display_info() # Accessing instance attributes
my_car.change_model("Corolla")
Car Brand: Toyota, Model: Camry
Car Brand: Toyota, Model: Corolla
✅ self.brand and self.model store data for each instance.
✅ self.display_info() is used to call another method in the same class.
✅ When my_car.change_model("Corolla") is called, self.model updates only for my_car, not for other instances.
Yes! self is just a convention, but you can technically use any word, like this or me:
def __init__(this, value):
However, using self is strongly recommended because it’s the widely accepted convention in Python.
Let me know if you need more clarification! 🚀