Class attributes can be accessed in two ways: through the class itself and through instances (objects) of the class. Here’s how each method works:
1. Accessing Class Attributes through the Class
You can access a class attribute directly using the class name followed by the attribute name.
class Dog:
species = "Canis lupus familiaris" # Class attribute
# Accessing class attribute through the class
print(Dog.species) # Output: Canis lupus familiaris
2. Accessing Class Attributes through Instances
You can also access class attributes using an instance of the class. However, if an instance attribute with the same name exists, the instance attribute will take precedence.
class Dog:
species = "Canis lupus familiaris" # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
# Creating an instance of the Dog class
dog1 = Dog("Buddy")
# Accessing class attribute through the instance
print(dog1.species) # Output: Canis lupus familiaris
Note on Precedence
If you define an instance attribute with the same name as a class attribute, the instance attribute will override the class attribute for that specific instance:
class Dog:
species = "Canis lupus familiaris" # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
self.species = "Dog" # Instance attribute overriding class attribute
dog1 = Dog("Buddy")
print(dog1.species) # Output: Dog (instance attribute takes precedence)
print(Dog.species) # Output: Canis lupus familiaris (class attribute)
In summary, class attributes can be accessed using either the class name or an instance of the class, but instance attributes can override class attributes when they share the same name.
