class Animal1class Animal:2 def __init__(self, name):3 self.name = name4 def speak(self):5 return "..."6class Dog(Animal):7 def speak(self):8 return "Woof"9rex = Dog("Rex")10print(rex.name, rex.speak())class Dog(Animal)rex, a Dogno __init__ hereno speak hereclass AnimalDog(Animal)Dog("Rex")__init__'Rex''Rex'"Woof"Rex Woofsuper()
Code card: pets.py; the highlighted line is the one runningBack and middle trays: the classes Animal and Dog, with their methodsFront tray: the object rex, with its own attribute nameTerminal: where print() writesEvery class and every object is a namespace of its own: the trays. rex stands at the front, its class Dog behind it, and Dog's base class Animal at the back; the rails show the links Python follows. Each step lights the parts it is about. A token hops along the step's arrow: __init__ comes from Animal because Dog has none, 'Rex' is stored on the object, name is found on the object and speak is found in Dog before Python ever reaches Animal's speak. That fixed search order, object, class, base classes, then object, is the method resolution order (MRO); super() continues the search one class further back.

Two classes

  1. Inheritance lets a new class reuse an existing one. Write class Dog(Animal) and Dog becomes a subclass (child) of Animal, its base class (parent). Dog gets everything Animal has, and can add or replace parts.

Making rex

Looking things up

The rules

Try it yourself

;; step 1/11
class Animal:          # the base class (parent)
    ...

class Dog(Animal):     # a subclass (child)
    ...

>>> issubclass(Dog, Animal)
True

A subclass does not copy its base class. Dog.__dict__ holds only speak; when Python cannot find an attribute in Dog it follows Dog.__bases__ to Animal. Add a method to Animal later and every Dog can use it at once. For special methods such as __init__, Python looks on the type of the object, not on the object itself, so the figure starts that search at Dog. For ordinary attributes such as name and speak it looks on the object first.