The self Parameter in Python

The self Parameter in Python

Kishore V


The self Parameter in Python

In Python, self is a reference to the current object (instance) of a class.

It allows methods inside a class to access and modify the object’s own data and behavior.

Whenever you work with instance variables or methods, self is required.

Using self to Access Object Properties

Attributes that belong to an object are accessed using the self keyword.

Example: Access Attributes with self

Output:

User: Arjun, Points: 120
Try it Yourself

Here:

  • self.username and self.points belong to the specific object p1
  • Each object has its own values

Why self Is Necessary

Without self, Python would not know which object’s data a method should use.

Example: Linking Methods to Objects

Output:

Neha
Karan
Try it Yourself

Each method call works on a different object, even though the same class is used.

Rule: self Must Be the First Parameter
In every instance method, self must be the first parameter.
Python automatically passes the current object when the method is called.

self Is a Convention, Not a Keyword

Technically, self can be named anything, but using self is strongly recommended for readability and consistency.

Example: Using a Different Name (Not Recommended)

Output:

Printer
Try it Yourself

Even though this works, using self makes the code easier for others to understand.

Accessing Multiple Properties with self

You can use self to access any number of object attributes.

Example: Display Object Information

Output:

HP | 16GB RAM | ₹65000
Try it Yourself

Calling One Method from Another Using self

Methods inside the same class can call each other using self.

Example: Method Calling Another Method

Output:

Hello Rohit, have a great day!
Try it Yourself

Our website uses cookies to enhance your experience. Learn More
Accept !