Understanding self and Instance References in Python
๐ Table of Contents
๐ Introduction
In Python, everything is an object. When you create a class instance, Python internally assigns a reference to that object.
Understanding self is essential to mastering Object-Oriented Programming (OOP).
self represents the current object instance inside a class.
๐ง What is an Object Reference?
When you write:
ref_variable = Test(5)
You are not storing the object directly. Instead, you are storing a reference (memory pointer) to that object.
๐ฝ Expand: Simple Analogy
Think of a house:
- Object = House
- Reference = Address of house
- Variable = Label holding the address
๐ Understanding self
Inside a class, Python automatically passes the instance as the first argument to methods.
That parameter is called self.
def display(self):
This means: "operate on the current object".
self.
๐ Basic Example
class Test:
def __init__(self, x):
self.x = x
def display(self):
print("Value of x:", self.x)
ref_variable = Test(5)
ref_variable.display()
๐ฝ Explanation
self.xstores instance-specific data- Each object has its own copy
- Methods use
selfto access that data
๐ง How Memory Works Internally
ref_variable -----> Object in Heap Memory
{
x = 5
}
Each time you create an object, Python allocates memory in the heap and returns a reference.
๐ Multiple Instances Example
class Test:
def __init__(self, x):
self.x = x
def show(self):
print(self.x)
a = Test(10)
b = Test(20)
a.show()
b.show()
Each object maintains its own state.
⚠️ Common Mistakes
❌ Forgetting self
def display():
print(x) # Error
Python will not know which object’s x you mean.
❌ Confusing class variable and instance variable
class Test:
x = 10 # class variable
This is shared across all instances.
๐ Advanced Concepts
classmethod vs self
class Test:
@classmethod
def show(cls):
print("Class method")
def instance_method(self):
print("Instance method")
self→ object levelcls→ class level
staticmethod
@staticmethod
def helper():
print("No self or cls needed")
๐ป CLI Output Example
$ python test.py Value of x: 5 10 20
๐ฝ How Python Executes This
1. Object is created in memory
2. Reference is stored in variable
3. Method call passes object automatically as self
๐ฏ Key Takeaways
selfrefers to the current object- Each instance has its own data
- Methods use self to access variables
- Variables outside class are references
- Python passes self automatically
๐ Final Thoughts
Once you understand self, Python OOP becomes significantly easier.
It is not just syntax—it is the way Python tracks object identity and behavior.
No comments:
Post a Comment