Sub topic 1
Subclasses and what they inherit
Inheritance lets one class reuse the attributes and methods of another. This chapter covers the syntax for creating a subclass, what a subclass receives from its parent, and what it does not receive. Later chapters cover lookup rules, overriding, and super() in detail.
Prerequisites
This chapter assumes you can already:
- Define a class and create instances from it.
- Write instance methods that use
selfand set instance attributes in__init__. - Define and call functions with positional and keyword arguments.
- Use f-strings and
print.
The core idea
A subclass (also called a child class or derived class) is a class created from another class, the parent (also called the base class or superclass). You name the parent in parentheses after the subclass name:
class Animal:
kingdom = "Animalia"
def __init__(self, name):
self.name = name
def describe(self):
return f"{self.name} belongs to {self.kingdom}"
class Dog(Animal):
pass
rex = Dog("Rex")
print(rex.name) # Rex
print(rex.describe()) # Rex belongs to Animalia
print(Dog.kingdom) # AnimaliaDog has an empty body, yet Dog("Rex") works. Calling Dog("Rex") runs the __init__ that Dog inherited from Animal. describe and kingdom are inherited the same way.
The relationship is called "is-a": a Dog is an Animal. Keep this phrase in mind. It is the main test for whether inheritance is the right design, and the last chapter returns to it.
What a subclass inherits
A subclass gets access to everything defined on its parent class:
| Parent member | Inherited? | Notes |
|---|---|---|
| Instance methods | Yes | Callable on subclass instances. |
| Class attributes | Yes | Shared with the parent, not copied. |
| `@classmethod` and `@staticmethod` | Yes | A classmethod receives the subclass as `cls`. |
| `__init__` and other dunder methods | Yes | Used unless the subclass defines its own. |
| Properties | Yes | They are class-level descriptors. |
| Instance attributes such as `self.name` | Indirectly | They exist only if the parent's `__init__` runs. |
The last row is the one that surprises people. Instance attributes belong to each object, not to the class. A subclass instance has self.name only because Animal.__init__ ran and assigned it. The sections below return to this.
The class hierarchy
Every class in Python 3 inherits from object. These two definitions are equivalent:
class Animal:
pass
class AnimalExplicit(object):
pass
print(Animal.__bases__) # (<class 'object'>,)__bases__ is a tuple of a class's direct parents. object supplies the defaults every instance has, such as __repr__, __eq__, and __hash__.
Arrows point from the parent to the child here. Inheritance is transitive: Dog gets members from Animal, and from object through Animal.
Adding new members in a subclass
A subclass can define methods and attributes the parent lacks. This is the simplest use of inheritance, called extending:
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def fetch(self, item):
return f"{self.name} fetches the {item}"
rex = Dog("Rex")
print(rex.fetch("ball")) # Rex fetches the ball
generic = Animal("Generic")
print(hasattr(generic, "fetch")) # FalseInheritance runs one way. Dog receives Animal's members, but Animal does not receive Dog's. Code that holds an Animal cannot assume fetch exists, even if the object happens to be a Dog.
Class attributes: shared, not copied
A class attribute lives on the class object. Subclasses see the parent's value through lookup. They do not get their own copy.
class Animal:
kingdom = "Animalia"
class Dog(Animal):
pass
print(Dog.kingdom) # Animalia
print("kingdom" in vars(Dog)) # False
print("kingdom" in vars(Animal)) # Truevars(Dog) lists only what Dog defines itself, and kingdom is not in it. Python finds the value by searching up to Animal. The next chapter explains that search.
Two consequences follow.
Changing the parent changes the children. If you rebind Animal.kingdom, every subclass that has not defined its own kingdom sees the new value.
Assigning on an instance or subclass shadows, and never modifies the parent.
class Animal:
kingdom = "Animalia"
class Dog(Animal):
pass
rex = Dog()
rex.kingdom = "Pets" # creates an instance attribute
Dog.kingdom = "Canines" # creates a class attribute on Dog
print(rex.kingdom) # Pets
print(Dog.kingdom) # Canines
print(Animal.kingdom) # AnimaliaEach assignment creates a new attribute on the object being assigned to. The parent's attribute is untouched.
The mutable class attribute trap
Shadowing happens only when you assign (rebind) a name. Mutating a shared object, such as appending to a list, changes the one object that every class refers to:
class Base:
tags = []
class A(Base):
pass
class B(Base):
pass
A.tags.append("from A")
print(B.tags) # ['from A']
print(Base.tags) # ['from A']A.tags is not a copy. It is the list owned by Base. There are two fixes:
- If each instance needs its own list, create it in
__init__withself.tags = []. - If each subclass needs its own class-level list, define one in each subclass body:
tags = [].
Inheriting `__init__`
If a subclass does not define __init__, it uses the parent's, as Dog("Rex") did earlier. The subclass call signature is then the parent's signature.
If a subclass does define __init__, that method replaces the parent's for subclass instances. Python does not call the parent's __init__ automatically:
class Base:
def __init__(self):
self.ready = True
class Child(Base):
def __init__(self):
pass # forgot to initialize the parent
child = Child()
try:
print(child.ready)
except AttributeError as exc:
print("AttributeError:", exc)The output is AttributeError: 'Child' object has no attribute 'ready'. The method Base.__init__ exists and is inherited, but Child.__init__ hides it, so self.ready is never assigned. This is the practical meaning of "instance attributes are inherited only if the parent's __init__ runs". The fix, super().__init__(), gets its own chapter section later.
Inherited classmethods see the subclass
A @classmethod receives the class it was called on, not the class where it was written. That makes alternative constructors work for subclasses with no extra code:
class Animal:
def __init__(self, name):
self.name = name
@classmethod
def create(cls, name):
return cls(name)
class Dog(Animal):
pass
pet = Dog.create("Rex")
print(type(pet).__name__) # DogDog.create runs the function defined on Animal, but cls is Dog, so the result is a Dog. If the method had hard-coded Animal(name), every subclass would return plain Animal objects. Prefer cls(...) in alternative constructors.
Name mangling and "private" attributes
Python has no true private members. A name that starts with two underscores and does not end with two underscores, such as __secret, is rewritten inside the class body to _ClassName__secret:
class Animal:
def __init__(self):
self.__secret = 42
class Dog(Animal):
def reveal(self):
return self.__secret # becomes self._Dog__secret
dog = Dog()
print(vars(dog)) # {'_Animal__secret': 42}
try:
dog.reveal()
except AttributeError as exc:
print("AttributeError:", exc)The attribute is stored as _Animal__secret, but Dog.reveal looks for _Dog__secret, so it fails. A single leading underscore, as in _secret, is only a convention meaning "internal, avoid using it from outside". It is not rewritten, and subclasses can use it normally. Use the single underscore for members that subclasses may need.
Inspecting a hierarchy
Three built-in tools help you see what is going on:
class Animal:
kingdom = "Animalia"
def describe(self):
return "an animal"
class Dog(Animal):
def fetch(self):
return "fetching"
print(Dog.__bases__) # (<class '__main__.Animal'>,)
print(sorted(vars(Dog))) # names defined on Dog only (plus bookkeeping names)
print(hasattr(Dog(), "describe")) # True
print([c.__name__ for c in Dog.__mro__]) # ['Dog', 'Animal', 'object']__bases__shows the direct parents.vars(cls)shows only what the class defines itself. It does not show inherited names.dir(obj)lists inherited names as well.__mro__shows the order in which Python searches classes, which a later chapter covers in full.
Output of sorted(vars(Dog)) includes extra names such as __doc__ and __module__, which Python adds to every class. Do not rely on its exact contents.
Common mistakes
- Expecting the parent to gain child methods. Inheritance only passes members down.
- Overriding
__init__and forgetting the parent's. The parent's attributes are missing and you getAttributeErrorlater, far from the cause. - Mutating a shared class-level list or dict. Every class and instance in the hierarchy sees the change.
- Using inheritance for "has-a" relationships. A
Carhas anEngine. It is not an engine. Use an attribute for that, as the last chapter explains. - Relying on
__namemangled attributes in subclasses. Use a single underscore instead.
Exercises
Exercise
Given class A: items = [], class B(A): pass, and class C(A): items = [], what do A.items, B.items, and C.items each contain after running B.items.append(1) and C.items.append(2)?
Show answer
A.items and B.items are the same list and contain [1]. B has no items of its own, so B.items finds the list owned by A, and the append changes it. C defines its own list, so C.items contains [2] and A is unaffected.
Exercise
A class Report defines @classmethod def build(cls, data): return Report(data). A subclass PdfReport(Report) calls PdfReport.build(data). What type is returned, and how do you change build so it returns the right type?
Show answer
It returns a plain Report, because the class name is hard-coded. Change the body to return cls(data) so that cls is PdfReport when called through the subclass.