Python self Parameter
🐍 Python self Parameter
The self parameter is a convention in Python used in object-oriented programming.
It represents the instance of the class and allows access to attributes and methods of that object.
🔍 Key Points About self
-
selfrefers to the current object. -
Must be the first parameter in instance methods, including
__init__(). -
Not a keyword, you can technically use other names, but
selfis standard. -
Required to access instance variables and methods.
✅ Basic Example
Explanation:
-
self.nameandself.ageare attributes of the objectp. -
Without
self, Python wouldn’t know which object’s variables to use.
🧠 Why self is Important
❌ This won’t work because Python doesn’t know these are instance attributes.
You must use self:
🔄 Accessing Methods via self
⚡ Calling Attributes Between Methods
🧩 self vs Class Variables
-
self.ramis unique for each object. -
brandis shared among all objects.
⚠ Notes
-
selfis not passed manually; Python passes it automatically. -
Can technically use another name, e.g.,
this, but do not — follow convention.
✅ Summary
| Feature | Description |
|---|---|
self |
Refers to the current object |
| Required in | All instance methods, including __init__() |
| Purpose | Access instance attributes & methods |
| Convention | Always use self |
🧪 Practice Tasks
-
Create a class
Employeeand useselfto assignnameandsalary. -
Add methods to display and update the salary using
self. -
Create two objects and test if their attributes are independent.
