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

  1. self refers to the current object.

  2. Must be the first parameter in instance methods, including __init__().

  3. Not a keyword, you can technically use other names, but self is standard.

  4. Required to access instance variables and methods.


✅ Basic Example


 

Explanation:

  • self.name and self.age are attributes of the object p.

  • 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.ram is unique for each object.

  • brand is shared among all objects.


⚠ Notes

  1. self is not passed manually; Python passes it automatically.

    obj.method() # Python passes obj as self
  2. 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 Employee and use self to assign name and salary.

  • Add methods to display and update the salary using self.

  • Create two objects and test if their attributes are independent.

You may also like...