Junior — Middle
What is the difference between variables declared at the class level and variables belonging to specific objects?
sobes.tech AI
Answer from AI
In Python, variables declared at the class level are called class attributes, and variables belonging to specific objects are called instance attributes.
- Class attributes are shared among all instances of the class. Changing such an attribute affects all objects unless the object has its own attribute with the same name.
- Instance attributes belong to a specific object and are stored in its
__dict__. They are unique to each object.
Example:
class MyClass:
class_var = 0 # class attribute
def __init__(self, value):
self.instance_var = value # instance attribute
obj1 = MyClass(10)
obj2 = MyClass(20)
print(obj1.class_var) # 0
print(obj2.class_var) # 0
MyClass.class_var = 5
print(obj1.class_var) # 5
print(obj2.class_var) # 5
obj1.instance_var = 15
print(obj1.instance_var) # 15
print(obj2.instance_var) # 20
Thus, class attributes are used to store common data, while instance attributes are for individual object properties.