Sobes.tech
Junior — Middle

What is the difference between class properties and specific object properties in Python?

sobes.tech AI

Answer from AI

Class properties (class attributes) in Python belong to the class itself and are shared among all its instances. They are defined inside the class body but outside of methods. If you change a class property, this change will be visible in all objects that have not overridden this property.

Properties of a specific object (instance attributes) belong only to that object and are usually defined inside the __init__ method or dynamically. They are unique to each instance and do not affect other objects of the class.

Example:

class MyClass:
    class_attr = 10  # class property

    def __init__(self, value):
        self.instance_attr = value  # object property

obj1 = MyClass(1)
obj2 = MyClass(2)

print(obj1.class_attr)      # 10
print(obj2.class_attr)      # 10
print(obj1.instance_attr)   # 1
print(obj2.instance_attr)   # 2

MyClass.class_attr = 20
print(obj1.class_attr)      # 20
print(obj2.class_attr)      # 20

obj1.instance_attr = 100
print(obj1.instance_attr)   # 100
print(obj2.instance_attr)   # 2