Lesson 24 / 49

Instance vs Class Attributes

Tell instance attributes from class attributes, and avoid surprises when changing shared class data.

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)        # different

Careful 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.