Curriculum
In Python, class attributes are variables or properties that are shared by all instances of a class. They are defined within the class, but outside of any method, and are accessed using the class name instead of an instance name.
Here’s an example to illustrate how class attributes work in Python:
class Person:
species = "human"
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 30)
p2 = Person("Jane", 25)
print(p1.species) # Output: human
print(p2.species) # Output: human
Person.species = "homo sapiens"
print(p1.species) # Output: homo sapiens
print(p2.species) # Output: homo sapiens
In the example above, we have a class Person with a class attribute species that is set to “human”. This attribute is defined outside of the __init__ method, which means it is shared by all instances of the class.
We then create two instances of the Person class (p1 and p2) and access the species attribute using the instance names. Since the attribute is a class attribute, we can access it using the class name (Person.species) as well.
Finally, we update the species attribute of the Person class to “homo sapiens”. This change is reflected in both p1 and p2, since they share the same class attribute.
Class attributes are useful when you want to define a property or variable that should be the same for all instances of a class. This can be helpful when you want to avoid having to repeat the same information in every instance of the class, and instead define it once at the class level.