Sub topic 1
Subclasses and what they inherit
Prerequisites
This chapter assumes you can:
- Define a class and create instances from it.
- Write instance methods that use
self. - Define and call functions with arguments.
- Use f-strings and
print.
What a subclass is
A subclass is a class that is built on top of another class, called the parent class (also called the base class or superclass). Write the parent's name in parentheses after the subclass name. The subclass then gets the parent's attributes and methods without copying any code.
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
return f"{self.name} makes a sound"
class Dog(Animal):
def speak(self):
return f"{self.name} barks"
print(Animal("Generic").speak()) # Generic makes a sound
print(Dog("Rex").speak()) # Rex barksDog has no __init__ of its own, so Dog("Rex") runs the __init__ it inherited from Animal. Dog does define speak(), so Dog instances use that version. Animal instances keep the original.
What gets inherited
A subclass inherits everything defined on the parent class itself:
- Methods, including special methods such as
__init__and__str__. - Class attributes, which are variables defined in the class body.
Instance attributes such as self.name are not stored on the class. They exist only after the parent's __init__ has run on an instance. That is why Dog("Rex") has a name: the inherited __init__ ran and set it.
Every class in Python also inherits from object, either directly or through its parents. This is where defaults like __repr__ and __eq__ come from.
The relationship between the classes
The diagram shows the "is-a" relationship. A Dog is an Animal, so it can be used wherever an Animal is expected.
Checking the relationship
Two built-ins report inheritance. isinstance(obj, cls) asks whether an object is an instance of a class or any of its subclasses. issubclass(sub, cls) asks the same about two classes. A later chapter covers these in detail. Here is a first look:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
pass
d = Dog("Rex")
print(isinstance(d, Animal)) # True
print(isinstance(d, Dog)) # True
print(issubclass(Dog, Animal)) # True
print(type(d) is Animal) # FalseThe last line shows the difference. type(d) is exactly Dog, so an exact comparison with Animal fails. isinstance() follows inheritance, so it is usually what you want.
Common errors
- Forgetting the parent in parentheses.
class Dog:creates an unrelated class. It has nonameand no inheritedspeak(). - Expecting instance attributes without
__init__running. If a subclass defines its own__init__and does not call the parent's, the parent's attributes are never set. The next chapters show how to fix this withsuper(). - Using
type(x) == Parentfor checks. This rejects every subclass. Useisinstance()instead.
Summary
- Write
class Child(Parent):to create a subclass. - The subclass can use the parent's methods and class attributes, and it can define its own.
- Instance attributes appear only when the code that sets them, usually the parent's
__init__, runs. isinstance()andissubclass()recognize inheritance.
Exercise
Given class Animal with __init__(self, name) and class Cat(Animal): pass, what does Cat("Tom").name return, and why? What does isinstance(Cat("Tom"), Animal) return?
Show answer
Cat("Tom").name returns "Tom". Cat defines no __init__, so it uses the one inherited from Animal, which sets self.name. isinstance(Cat("Tom"), Animal) returns True because isinstance accepts instances of subclasses.
Exercise
Write a class Bird(Animal) that overrides speak() to return the name followed by " chirps". What does Bird("Tweety").speak() print when passed to print?
Show answer
class Bird(Animal): def speak(self): return f"{self.name} chirps" print(Bird("Tweety").speak()) prints "Tweety chirps". Bird inherits _init_ from Animal, so self.name is set, and its own speak() replaces the parent version for Bird instances.