After this lesson you can build a new class on top of an existing one, change what you need, and keep the rest.
Reusing a class
Imagine the library has members, and some of them are staff who can do everything a member does plus a little more. Copying the whole Member class into a new Staff class would duplicate code, and every fix would have to be made twice. Inheritance avoids that: a new class can start from an existing one.
The existing class is the parent (or base class). The new one is the child (or subclass). You name the parent in parentheses:
class Member:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}"
class Staff(Member):
pass
helper = Staff("Daniel")
print(helper.name)
print(helper.greet())Daniel
Hello, DanielStaff has an empty body, yet it has __init__ and greet, because it inherited them.
Adding and overriding methods
A subclass can add new methods, and it can override an inherited one by defining a method with the same name:
class Staff(Member):
def greet(self):
return f"Hello, {self.name} (library staff)"
def can_edit_catalogue(self):
return True
reader = Member("Asha")
helper = Staff("Daniel")
print(reader.greet())
print(helper.greet())
print(helper.can_edit_catalogue())Hello, Asha
Hello, Daniel (library staff)
TrueWhen Python looks for helper.greet, it checks the Staff class first and finds the override. For reader it finds the Member version. Member does not have can_edit_catalogue, so asking a plain member for it would be an error.
Extending __init__ with super()
Suppose staff also need an employee number. The subclass needs its own __init__, but it still wants the parent to set up name. super() gives you the parent, so you can call its method:
class Staff(Member):
def __init__(self, name, employee_number):
super().__init__(name)
self.employee_number = employee_number
def greet(self):
base = super().greet()
return f"{base} - staff no. {self.employee_number}"
helper = Staff("Daniel", 7)
print(helper.name)
print(helper.greet())Daniel
Hello, Daniel - staff no. 7Two uses of super() appear here. In __init__ it runs the parent's setup. In greet it reuses the parent's answer and adds to it. If you write your own __init__ in a subclass and forget super().__init__(...), the parent's attributes are never created.
Checking relationships
isinstance accepts a parent class and says yes for objects of any subclass. issubclass compares two classes. The __mro__ attribute shows the order Python searches for a method:
print(isinstance(helper, Staff))
print(isinstance(helper, Member))
print(isinstance(reader, Staff))
print(issubclass(Staff, Member))
print([cls.__name__ for cls in Staff.__mro__])True
True
False
True
['Staff', 'Member', 'object']Every class ultimately inherits from object, which is why object ends the list.
More than one level
A subclass can itself have subclasses:
class Librarian(Staff):
def greet(self):
return super().greet() + " (head librarian)"
head = Librarian("Elena", 1)
print(head.greet())
print([cls.__name__ for cls in Librarian.__mro__])Hello, Elena - staff no. 1 (head librarian)
['Librarian', 'Staff', 'Member', 'object']Each super().greet() passes the call up one level, and the strings are added on the way back. Keep hierarchies shallow, though. Two or three levels are easy to follow, and ten are not.
When inheritance is the right tool
Use it when the child really is a kind of the parent: a staff member is a member. When the relationship is has a, such as a library having books, put the books inside the library object instead. Beginners often inherit just to borrow a few methods, and it ties two unrelated classes together.
A video version of this topic is in the video course at /learn/python/.
Common mistakes
- Forgetting
super().__init__(). The parent's attributes are then missing, and later code fails withAttributeError. - Repeating the parent's setup by hand. It works until the parent changes, then the two drift apart.
- Overriding with a different signature. If code calls
greet()on any member, a subclass that demands an extra argument breaks it. - Inheriting for convenience. If you cannot say "X is a Y" and mean it, use an attribute instead.
- Building deep chains. Hard to read and hard to change. Keep hierarchies small.
Exercise
Write a class Shape with an attribute name and a method describe() that returns "<name> with area <area>", calling a method area() that returns 0 in Shape. Write a subclass Rectangle that takes width and height, calls super().__init__("rectangle") and overrides area(). Print Rectangle(3, 4).describe().
Show one possible answer
class Shape:
def __init__(self, name):
self.name = name
def area(self):
return 0
def describe(self):
return f"{self.name} with area {self.area()}"
class Rectangle(Shape):
def __init__(self, width, height):
super().__init__("rectangle")
self.width = width
self.height = height
def area(self):
return self.width * self.height
print(Rectangle(3, 4).describe())rectangle with area 12Key points
- A subclass is written as class Child(Parent) and gets every attribute and method of the parent.
- A subclass can override a method by defining one with the same name.
- super() lets the subclass call the parent's version, which is how __init__ is usually extended.
- isinstance(obj, Parent) is True for objects of subclasses, and issubclass checks classes directly.
- Use inheritance for a real 'is a' relationship, and prefer plain objects held inside another object when the relationship is 'has a'.