Multiple Inheritance
Learn about the multiple inheritance in Python.
Multiple inheritance is a touchy subject. In principle, it’s simple: a subclass that inherits from more than one parent class can access functionality from both of them. In practice, it requires some care to be sure any method overrides are fully understood.
Tip: As a humorous rule of thumb, if we think we need multiple inheritance, we’re probably wrong, but if we know we need it, we might be right.
The mixin design pattern
The simplest and most useful form of multiple inheritance follows a design pattern called the mixin. A mixin class definition is not intended to exist on its own, but
is meant to be inherited by some other class to provide extra functionality. For example, let’s say we wanted to add functionality to our Contact
class that allows sending an email to self.email
.
Sending emails is a common task that we might want to use in many other classes. So, we can write a simple mixin class to do the emailing for us:
class Emailable(Protocol):email: strclass MailSender(Emailable):def send_mail(self, message: str) -> None:print(f"Sending mail to {self.email=}")# Add e-mail logic here
Python protocol
The MailSender
class doesn’t do anything special (in fact, it can barely function as a standalone class, since it assumes an attribute it doesn’t set). We have two classes because we’re describing two things:
- Aspects of the host class for a mixin
- New aspects the mixin provides to the host
We needed to create a hint, Emailable
, to describe the kinds of classes our MailSender
mixin expects to work with.
This kind of type hint is called a protocol; protocols generally ...