5. Class vs instance attributes
An attribute written directly in the class body, outside any method, is a class attribute:
- It is created once, when the class is defined.
- It is shared by every instance of the class.
- You read it through the class (
Dog.species) or through an instance (dog.species).
Use a class attribute for values that are the same for all instances, such as a constant or a default.
An instance attribute with the same name shadows the class attribute. Assigning dog.species = "wolf" does not change the class; it creates an attribute on that dog only:
Changing the class attribute affects every instance that does not have its own attribute with that name:
A mutable class attribute such as a list is shared too. Calling first.members.append(...) changes the same list that every instance sees. For per-instance data, create the value inside __init__ with self.attribute = value.
Coming from JavaScript? A class attribute is like a static property, but instances can read it directly: dog.species works without Dog.species.
Read a class attribute
Define a class Dog with a class attribute species = "canine" directly in the body, outside any method. Print it through the class: Dog.species.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Read it through an instance
Define Dog with the class attribute species = "canine". Create dog = Dog() and print dog.species.
The instance has no species of its own, so Python finds the class attribute.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Shadow it on one instance
Define Dog with the class attribute species = "canine". Create dog = Dog(), then assign dog.species = "wolf". Print dog.species, then print Dog.species.
The assignment creates an attribute on that instance; the class attribute is unchanged.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
Change it for every instance
Define Dog with the class attribute species = "canine". Change it through the class to "wolf", then create first = Dog() and second = Dog(). Print each dog's species on its own line.
Neither dog has its own species, so both read the new class value.
Print exactly:
Create a free account to save your progress and unlock chapter 2.
A mutable class attribute is shared
Define Team with the class attribute members = [] directly in the body, not inside __init__. Create first = Team() and second = Team(), then call first.members.append("Ada"). Print second.members.
Both names point to the same list, so the change made through first is visible through second.
Print exactly:
Create a free account to save your progress and unlock chapter 2.