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:
Here:
self.usernameandself.pointsbelong to the specific objectp1- 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:
Karan
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:
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:
Calling One Method from Another Using self
Methods inside the same class can call each other using self.
