Python Class & Instance Attributes
An instance attribute is a value that belongs to one object. A class attribute is a value set in the class body.
Own values from __init__
name and age are set inside __init__. Each dog gets its own pair of values.
class Dog:
species = "dog"
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
print(buddy.name)
print(coco.name)A shared value from the class body
species is set in the class body, outside __init__. Both dogs read the same value.
class Dog:
species = "dog"
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
print(buddy.species)
print(coco.species)Change the shared value through the class
Dog.species sets the value on the class. Every dog now reads the new value.
class Dog:
species = "dog"
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
Dog.species = "domestic dog"
print(buddy.species)
print(coco.species)One object gets its own value
Coco now has a species value of her own. That value shadows the class value for Coco.
class Dog:
species = "dog"
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
coco.species = "show dog"
print(coco.species)
print(buddy.species)Example
class Dog:
species = "dog"
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
coco = Dog("Coco", 2)
print(buddy.name)
print(buddy.species)
print(coco.name)
print(coco.species)
coco.species = "show dog"
print(coco.species)
print(buddy.species)Key points
- Instance attribute: a value that belongs to one object
- Class attribute: a value set in the class body, shared by all objects
- Use Dog.species to change the shared value for the whole class
- Shadow rule: Python reads an object's own attribute before the class one
In this example, species sits in the class body, so it is shared. __init__ gives each dog its own name and age. The first print lines show two different names. Both dogs read the same species, dog. Then coco.species gives Coco a value of her own. That value shadows the class value for Coco only. Buddy still reads the shared value, dog.
Note
Setting an attribute on one object shadows the class value for that object only.
Other objects still read the class value.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Coco has no species value of her own. After Dog.species = "domestic dog", what is coco.species?