Python Instance and class variables
Table of Contents
Description
In OOP, variables are categorized based on how and where they are defined:
Instance Variables – Belong to the object (instance) and are defined inside methods using self.
Class Variables – Shared across all instances; defined inside the class but outside any method.
Local Variables – Defined within methods and exist only during method execution.
Static Variables – Another term used for class variables in some contexts.
Prerequisites
- Basic understanding of Python syntax
- Understanding of functions and classes
- Familiarity with self keyword
Examples
Here's a simple program in Python:
✅ Instance Variable class Student: def __init__(self, name, grade): self.name = name # Instance variable self.grade = grade # Instance variable s1 = Student("Alice", "A") print(s1.name) # Output: Alice ✅ Class Variable class Student: school_name = "ABC School" # Class variable (shared) def __init__(self, name): self.name = name # Instance variable s1 = Student("Tom") s2 = Student("Jerry") print(s1.school_name) # Output: ABC School print(s2.school_name) # Output: ABC School # Changing class variable Student.school_name = "XYZ School" print(s1.school_name) # Output: XYZ School ✅ Local Variable class Calculator: def add(self, a, b): result = a + b # Local variable return result c = Calculator() print(c.add(3, 4)) # Output: 7 ✅ Difference Between Instance and Class Variable class Car: wheels = 4 ️ # Class variable def __init__(self, brand): self.brand = brand # Instance variable car1 = Car("Toyota") car2 = Car("Honda") car1.wheels = 6 # Creates a new instance variable for car1 only print(car1.wheels) # Output: 6 print(car2.wheels) # Output: 4 print(Car.wheels) # Output: 4Real-World Applications
Instance Variables store data specific to a user (e.g., user profile info).
Class Variables are used for constants or shared counters (e.g., number of instances).
Local Variables are temporary and used inside methods for calculations, temporary data storage, etc.
Where topic Can Be Applied
Web frameworks (e.g., Django models using instance/class variables)
Game dev: Object properties like health, speed
Simulation systems: Vehicle types, weather conditions
OOP-based systems like banking, inventory, school management
Resources
WatchTopic video source
A comprehensive video
Interview Questions
What is the difference between instance and class variables?
How do you declare a class variable in Python?
What happens if you override a class variable in an instance?
Can local variables be accessed outside a method?
How are static variables handled in Python?