Single Inheritance · Lecture 01 · 12 min
Single Inheritance
A class can inherit from one parent class, forming an is-a hierarchy that issubclass() checks between classes and isinstance() checks for instances.
The idea: “is a”
Inheritance models a relationship between classes: a child class is a more specialized version of its parent. A circle is an ellipse (one whose two radii happen to be equal), an ellipse is a shape, a square is a rectangle, and so on. The child class (also called a subclass or derived class) automatically gets everything the parent (the superclass or base class) defines, and can then add to it or change parts of it.
This lesson doesn’t add any behavior yet. We only build a hierarchy and look at how Python records and checks the relationships, because that’s what the rest of the section builds on.
Building a hierarchy
To inherit from a class, put its name in parentheses after the new class name. With single inheritance, each class names exactly one parent:
class Shape:
pass
class Ellipse(Shape):
pass
class Circle(Ellipse):
pass
class Polygon(Shape):
pass
class Rectangle(Polygon):
pass
class Square(Rectangle):
pass
class Triangle(Polygon):
passThat gives us this tree. Each arrow points from a child to its parent:
issubclass(): a relationship between classes
issubclass(A, B) asks whether class A is B or inherits from it, directly or through any number of intermediate classes:
print(issubclass(Ellipse, Shape)) # direct parent
print(issubclass(Square, Shape)) # Square -> Rectangle -> Polygon -> Shape
print(issubclass(Square, Ellipse)) # different branch
print(issubclass(Shape, Shape)) # a class counts as a subclass of itselfThe word “subclass” is a good reminder that this is about classes, not instances. Passing an instance is an error:
s = Shape()
e = Ellipse()
try:
issubclass(e, s)
except TypeError as ex:
print('TypeError:', ex)isinstance(): is this object one of those?
For objects, use isinstance(obj, cls). It’s True when the object’s class is cls or any subclass of it. Since every Square is also a Rectangle, a Polygon and a Shape, a square object is an instance of all four:
sq = Square()
for cls in (Square, Rectangle, Polygon, Shape, Ellipse):
print(f'{cls.__name__:<10}', isinstance(sq, cls))The second argument can also be a tuple of classes, meaning “any of these”. Since Python 3.10 a union written with | works too:
c = Circle()
print(isinstance(c, (Polygon, Ellipse)))
print(isinstance(c, Polygon | Ellipse)) # Python 3.10+isinstance() versus type()
type(obj) gives the exact class an object was created from, nothing more. That makes a type(...) is ... check stricter than isinstance:
print(type(sq))
print(type(sq) is Rectangle) # False: its class is exactly Square
print(isinstance(sq, Rectangle)) # True: a Square is a RectangleThe whole point of inheritance is that a child can be used anywhere the parent is expected. Code that receives “a rectangle” should accept squares too, so prefer isinstance() for checks like this. Reach for type(obj) is X only when you really need to exclude subclasses.
Looking at the hierarchy
Python keeps the links in plain attributes you can inspect. __bases__ holds a class’s direct parents, __subclasses__() lists its direct children, and __mro__ lists the class followed by all of its ancestors, nearest first:
print(Square.__bases__)
print(Polygon.__subclasses__())
print(Square.__mro__)__mro__ stands for method resolution order: the order in which Python searches classes when it looks up an attribute or method. With single inheritance it’s simply the chain from the class up to the root, as the output shows. It comes back in the lessons on overriding and super(), because it decides which method runs. (With multiple inheritance, where a class can have several parents, the order is computed by an algorithm called C3, but that isn’t needed here.)
Every class has a parent
Notice the last entry in that MRO: object. Even though Shape didn’t name a parent, it has one:
class Person:
pass
print(Person.__bases__)
print(issubclass(Person, object), issubclass(Square, object))
print(isinstance(Person(), object), isinstance(sq, object))In Python 3, a class that doesn’t list a parent implicitly inherits from the built-in class object. (Yes, object is a class, despite its name.) So every class, and therefore every object, is ultimately an object. The next lesson looks at what that root class provides.
You’ll still see class Person(object): in older code. In Python 2 that was needed to get a “new-style” class. In Python 3 it means exactly the same as class Person:, so you can leave it out.
Key takeaways
- Inheritance expresses an is-a relationship between classes. With single inheritance each class has exactly one parent.
issubclass(A, B)compares classes; it’sTruefor direct and indirect parents, and forA is B.isinstance(obj, B)checks an object; it’sTrueif the object’s class isBor any subclass ofB. It also accepts a tuple, or (3.10+) a|union.type(obj)is the exact class only. Preferisinstanceso that subclasses are accepted.__bases__,__subclasses__()and__mro__let you inspect the hierarchy.__mro__is the lookup order for attributes.- Every class implicitly inherits from
object.