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.

Loading editor…

Accessing Instance Variables

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

Loading editor…

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.

Loading editor…

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

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.