Nearby lessons
103 of 159Python - 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.
Accessing Instance Variables
Instance variables are accessed using self inside the class and using the object reference outside the class.
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.
Summary
| Topic | Meaning |
|---|---|
| Instance variable | Variable tied to a specific object |
| self | Used to access object data |
| del | Deletes 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 QuestionsProgress: 0 / 6