Junior — Middle
How do static variables differ from object variables in classes?
sobes.tech AI
Answer from AI
In Python, class static variables (class attributes) are shared among all instances of the class, whereas object variables (instance attributes) belong to a specific object.
- Static variables (class attributes) are declared inside the class but outside of methods, and are accessible through the class and all its objects.
- Object variables are created inside methods (usually in
__init__) viaselfand are unique to each instance.
Example:
class MyClass:
static_var = 0 # class attribute
def __init__(self, value):
self.instance_var = value # object attribute
obj1 = MyClass(10)
obj2 = MyClass(20)
print(obj1.static_var) # 0
print(obj2.static_var) # 0
obj1.static_var = 5 # creates an object attribute for obj1, not changing the class attribute
print(obj1.static_var) # 5
print(obj2.static_var) # 0
print(MyClass.static_var) # 0
print(obj1.instance_var) # 10
print(obj2.instance_var) # 20
Thus, static variables are used to store data common to all objects, while object variables are for individual data of each instance.