Instance Methods & Variable Scopes
Objects aren't just passive data holders—they can perform actions. In Python, functions defined inside a class that operate on an object's data are called Instance Methods.
In this lesson, we will explore how instance methods work under the hood and clarify the vital difference between Instance Variables and Local Variables.
1. Learning Objective
By the end of this lesson, you will understand:
- What an Instance Method is and why every instance method requires
selfas its first parameter. - How Python translates
s1.introduce()toStudent.introduce(s1)behind the scenes. - The difference in memory lifecycle between Instance Variables (
self.x) and Local Variables (x). - Why local variables disappear as soon as a method finishes executing.
2. Why This Concept Exists
In procedural programming, if you have a calculate_grade(student_name, marks, attendance) function, you must manually pass every piece of data into the function every single time.
With Instance Methods, because the method belongs to the object, it already has direct access to all of that object's internal data through self. You don't need to pass name, marks, or attendance repeatedly!
3. Common Beginner Confusions
Confusion 1: "Why do I have to write def introduce(self): if I don't pass any arguments when calling s1.introduce()?"
- Answer: When you call
s1.introduce(), Python automatically transforms your call intoStudent.introduce(s1). Python silently passess1(the object reference) as the first argument intoself.
Confusion 2: "Can I access a variable defined in __init__ inside another method?"
- Answer: YES, if it is an Instance Variable (
self.name). NO, if it is a local variable (temp_val = 100). Local variables vanish when__init__finishes.
4. Mental Model: Remote Control Buttons & Temporary Scratchpad
-
Remote Control Buttons (Instance Methods):
- Imagine a Smart TV object. Pressing the
.mute()button on Remote #1 mutes TV #1 because Remote #1 passes its TV address (self) to the mute instruction.
- Imagine a Smart TV object. Pressing the
-
Permanent Badge vs. Temporary Scratchpad:
- Instance Variable (
self.name): Engraved on a plastic ID badge clipped to the object in Heap RAM. It stays alive as long as the object exists. - Local Variable (
temp_calc = x + y): Written on a paper sticky note on a worker's desk (Stack Frame). As soon as the worker finishes the task, the sticky note is thrown in the trash.
- Instance Variable (
5. Internal Python Execution Flow
Let's trace how Python executes an instance method call:
Code Executed: s1.display_marks()
↓ Step-by-Step Translation:
1. Python reads s1.display_marks().
2. Python looks up the class of s1 -> finds class 'Student'.
3. Python rewrites the expression into: Student.display_marks(s1)
4. Python opens function display_marks() in class Student.
5. Parameter 'self' receives reference s1 (Address 0x9000).
6. Inside method: self.marks resolves to 0x9000 -> fetches 85.
7. Method finishes and control returns to main program.
6. Memory Visualization: Instance vs. Local Variable Lifespan
RAM Layout: Instance Variable (Heap) vs Local Variable (Stack)
calculate_discount() STACK FRAME
discount_rate = 0.10
(TEMPORARY - Destroyed when method ends!)
HEAP OBJECT (Address 0x9000)
self.price = 500
self.title = "Python Book"
(PERMANENT - Stored in object memory!)
7. Python Code Implementation
class Student:
def __init__(self, name, marks):
# Instance Variables (Stored on Heap Object)
self.name = name
self.marks = marks
# Instance Method
def calculate_final_score(self, bonus):
# 'bonus' is a Local Parameter Variable
# 'passing_cutoff' is a Local Variable
passing_cutoff = 40
total = self.marks + bonus # Accessing instance variable self.marks
if total >= passing_cutoff:
return f"{self.name} Passed with total score: {total}"
else:
return f"{self.name} Failed with total score: {total}"
# Usage
s1 = Student("Sai", 35)
# Calling instance method passing 10 as bonus
result = s1.calculate_final_score(10)
print(result)
# Trying to access local variable outside method:
# print(passing_cutoff) # Throws NameError!
Output:
Sai Passed with total score: 45
8. Line-by-Line Execution Analysis
Line: result = s1.calculate_final_score(10)
- Translation: Python executes
Student.calculate_final_score(s1, 10). - Stack frame created:
selfreceives references1,bonusreceives integer10.
Line: passing_cutoff = 40
- Local allocation:
passing_cutoffis created insidecalculate_final_scorestack frame.
Line: total = self.marks + bonus
- Lookup:
self.marksnavigates heap references1to fetch35.bonusfetches10.totalbecomes45.
Method Completion:
- Cleanup: The stack frame containing
passing_cutoff,bonus, andtotalis destroyed. - Preservation:
self.nameandself.marksremain safely stored inside objects1on Heap RAM.
9. Before / After Memory Visualization
During calculate_final_score(10) Execution
- Stack Frame:
self→s1,bonus = 10,passing_cutoff = 40. - Heap: Object
s1containsname = "Sai",marks = 35.
After Method Completion
- Stack Frame: Destroyed!
bonusandpassing_cutoffno longer exist in memory. - Heap: Object
s1still containsname = "Sai",marks = 35.
10. Illustration Prompt for Diagram Generation
Excalidraw Diagram Prompt: A hand-drawn diagram illustrating Instance Method Execution & Variable Scope. Show a call box labeled "s1.calculate_final_score(10)". Draw a transformation arrow rewriting it to "Student.calculate_final_score(self=0x9000, bonus=10)". On the right, draw a Heap box labeled "Student Object 0x9000" containing "self.name = Sai", "self.marks = 35". On the left, draw a temporary red stack frame box labeled "Local Scope (Temporary)" containing "bonus=10" and "passing_cutoff=40" with a trash icon indicating memory cleanup upon function return. White background, hand-drawn style, colors: Red (Temporary Stack), Green (Permanent Heap), Blue (Transformations).
Quick Summary
- Instance Methods are functions defined inside a class that operate on specific object instances.
- Python automatically rewrites
obj.method()toClass.method(obj), passingobjintoself. - Instance Variables (
self.x) live in Heap RAM inside the object as long as the object exists. - Local Variables (
x) live in Stack RAM inside the method call frame and are destroyed as soon as the method returns.