Junior — Middle
What is the difference between a class property and a property of a specific object within the program code?
sobes.tech AI
Answer from AI
A class property is an attribute that belongs to the class itself and is common to all its instances. An object property is an attribute that belongs to a specific instance of the class.
If you change a class property, this change will be visible in all objects that have not overridden this property themselves. If you change an object property, this change will only affect that specific instance.
Example:
class MyClass:
class_attr = 10 # class property
obj1 = MyClass()
obj2 = MyClass()
print(obj1.class_attr) # 10
print(obj2.class_attr) # 10
obj1.class_attr = 20 # creates an object property for obj1
print(obj1.class_attr) # 20 (object property)
print(obj2.class_attr) # 10 (class property)
print(MyClass.class_attr) # 10
MyClass.class_attr = 30
print(obj2.class_attr) # 30 (updated class property)
print(obj1.class_attr) # 20 (object property did not change)
Thus, class properties define common values, while object properties are individual for each instance.