Lesson 24 / 47
Instance vs Class Attributes
Data that belongs to one object vs data shared by all objects of a class.
Two kinds of attributes
Instance attributes (set via self.x = ...) differ per object. Class attributes are defined on the class and shared by every instance.
class Dog:
species = "Canis familiaris" # class attribute
def __init__(self, name):
self.name = name # instance attribute
a = Dog("Rex")
b = Dog("Fido")
print(a.species, b.species) # same for both
print(a.name, b.name) # differentCareful with mutation
Changing a class attribute through the class (Dog.species = ...) affects all instances; setting it on one instance (a.species = ...) only shadows it for that object.