The object-oriented concept of a “mixin” is used in Python, as in many programming languages (but not all).
The Python concept of a mixin doesn’t quite literally conform to the Wikipedia definition of a mixin, but it’s close.
Usually a subclass is a version of the superclass. In the example below, a VW literally is a Car, which is why it inherits from Car.
However, sometimes a parent class is added just to provide a bit of functionality. The class providing the functionality is then known as a mixin.
class Car:
def drive(self):
print("Vroooom")
class Alarm:
def sound_alarm(self):
print("Woo-woo-woo")
class VW(Car, Alarm):
pass
herbie = VW()
herbie.drive()
herbie.sound_alarm()
Vroooom
Woo-woo-woo
While a VW is a type of Car, it’s not really a type of Alarm. The Alarm class is added as a superclass purely to provide some functionality; it is a mixin.
Leave a Reply