Nearby lessons

103 of 159

Python - Instance Variables

📌 What You Will Learn
  • Understand what instance variables are
  • Know the three places where instance variables can be declared
  • Access instance variables using self and the object reference
  • Delete instance variables using the del keyword

What Are Instance Variables?

Instance variables are variables whose values can change from object to object.

Each object gets its own copy of instance variables.

Where Can They Be Declared?

  • Inside the constructor using self
  • Inside an instance method using self
  • Outside the class using the object reference

Example

Here, eno, ename, and esal are instance variables initialized inside the constructor.

🐍Code Cell
1class Employee:
2 def __init__(self):
3 self.eno = 100
4 self.ename = "Durga"
5 self.esal = 10000
6 
7 
8e1 = Employee()
9print(e1.eno, e1.ename, e1.esal)
Output
100 Durga 10000

Accessing Instance Variables

Instance variables are accessed using self inside the class and using the object reference outside the class.

🐍Code Cell
1class Student:
2 
3 def __init__(self, name):
4 self.name = name
5 
6 def display(self):
7 print("Inside class:", self.name)
8 
9 
10s = Student("Sunny")
11s.display()
12print("Outside class:", s.name)
Output
Inside class: Sunny
Outside class: Sunny

Deleting and Accessing

We can delete instance variables using del self.variableName inside the class or del object.variableName outside the class.

After deletion, accessing the variable raises an AttributeError.

🐍Code Cell
1class Test:
2 def __init__(self):
3 self.a = 10
4 self.b = 20
5 
6 
7t = Test()
8print(t.a)
9del t.a
10print(t.a)
Output
10
AttributeError: 'Test' object has no attribute 'a'

Summary

Topic Meaning
Instance variableVariable tied to a specific object
selfUsed to access object data
delDeletes instance variables
📝 Key Takeaways
  • Instance variables are variables whose values can change from object to object
  • Each object gets its own copy of instance variables
  • They can be declared inside the constructor, inside an instance method, or outside the class
  • Access them with self inside the class and with the object reference outside the class
  • Delete them with del self.variable or del object.variable

🧠 Test Your Knowledge

6 Questions
Progress: 0 / 6