What is self in Python? – Beginner Friendly Guide
self is one of the most important concepts in Python ObjectOriented Programming (OOP). Beginners often get confused about what self really
means. This tutorial explains self in a very simple, practical, and easy-to-understand
way.
Simple Definition
self refers to the current object (instance) of a class.
In simple words:
selfmeans “this object”.
Real-Life Analogy
If a person says:
"I am learning Python"
Here "I" refers to that person.
In Python:
self= the object that is calling the method
Basic Example
class Student:
def greet(self): print("Hello Student") s = Student() s.greet()Internal Working
Student.greet(s)So internally Python converts:
self = s
Example with Variables
class Student:
def set_name(self, name): self.name = name def show_name(self): print(self.name) s1 = Student()
s1.set_name("Chandan")
s1.show_name() s2 = Student()
s2.set_name("Amit")
s2.show_name()Output
1Chandan AmitEach object stores its own data using
self.
Why
selfis Important?
- Identifies the current object
- Stores object data
- Accesses instance variables
- Accesses instance methods
- Supports object-oriented programming
One-Line Explanation
selfis the reference to the current object of the class.
Important Points
selfis not a keyword- It is passed automatically by Python
- Must be first parameter in instance methods
- Standard convention is to use the name
self
Common Beginner Mistakes
- Forgetting
selfin method parameters- Using variables without
self.- Confusing local variables with instance variables
- Trying to access instance variables directly
Interview Question
Q: What is self in Python?
A:
selfis a reference to the current object of the class and is used to access variables and methods of that object.
Comparison with Java
Python Java self this
Easy Analogy
Each object is a person
self= “me” for that person
Conclusion
selfconnects class methods to objects. It allows each object to store its own data and behave independently. Understandingselfis essential to master Python OOP concepts.Without
2self, object-oriented programming in Python is not possible.
Related Topics
- Python Classes and Objects
- Constructors in Python
- Inheritance in Python
- Method Overriding
- super() keyword
- Encapsulation in Python
Happy Learning Python!
Follow this blog for Python, Automation, and Playwright tutorials.
No comments:
Post a Comment