Sobes.tech
Junior

What is the difference between a class attribute and an object attribute?

sobes.tech AI

Answer from AI

Class attributes belong to the class itself and are shared among all its instances. Object (instance) attributes belong to a specific instance of the class and are unique to that instance.

Attribute Description Access Modification
Class attribute Belongs to the class, common for all instances ClassName.attribute or object.attribute Changes for all instances when modified via the class
Object attribute Belongs to a specific instance, unique to it object.attribute Changed only for that particular instance

Example:

class Dog:
    species = "Canis familiaris"  # Class attribute

    def __init__(self, name, age):
        self.name = name  # Object attribute
        self.age = age    # Object attribute

# Creating two instances
dog1 = Dog("Buddy", 3)
dog2 = Dog("Lucy", 5)

# Access to class and object attributes
print(dog1.species)  # Canis familiaris
print(dog2.species)  # Canis familiaris
print(dog1.name)     # Buddy
print(dog2.name)     # Lucy

# Changing class attribute via class
Dog.species = "Domestic dog"
print(dog1.species) # Domestic dog
print(dog2.species) # Domestic dog

# Changing object attribute
dog1.age = 4
print(dog1.age) # 4
print(dog2.age) # 5 (unchanged)

# Assigning an attribute with the same name as a class attribute to an instance
# Creates an object attribute that "hides" the class attribute for that instance
dog1.species = "Wild dog"
print(dog1.species) # Wild dog (object attribute)
print(dog2.species) # Domestic dog (class attribute)
print(Dog.species)  # Domestic dog (class attribute)