Join us and get access to thousands of tutorials and a community of expert Pythonistas.
This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.
Distinguishing Mixins From Abstract Base Classes
00:00
How can you distinguish mixins from abstract base classes? The most obvious answer is that an abstract base class, often referred to as an ABC, inherits from the module abc, abc the module in lowercase, ABC the class that it inherits from in all uppercase, and also an abstract base class has abstract methods, which is often the point of inheriting from the superclass ABC.
00:27 This is the clearest way to distinguish both. It’s also important to understand that there’s a main distinction in the semantics of each type of class. An abstract base class is a class you create where you essentially establish a contract with the user.
00:45
The abstract methods in an abstract base class, they specify the methods that you must define in your subclasses in order to be able to fully satisfy the contracts. For example, the class Sequence that you can see on the screen is mimicking the abstract base class that’s available in the module collections.abc from the standard library.
01:09
Because the class Sequence inherits from ABC, this tells you that if you want to inherit from Sequence, then you must implement all of the methods that are tagged with the decorator @abstractmethod, which in this case are the .__getitem__() and the .__len__().
01:26
And from there, you can say that your class is a sequence. And if you try to inherit from the abstract base class Sequence, but you forget any of those two dunder methods, you get a runtime error because the ABC checks whether you have implemented the abstract methods or not.
01:45
And this is diametrically opposed to mixin classes because the mixin class provides the implementation you want. You just inherit from it and you automatically get this new behavior. So while an abstract base class essentially creates a contract that you must satisfy in order to be able to claim that you have a certain quality, for example, you need .__getitem__() and .__len__() to be able to say you’re a sequence, a mixin class on the other hand just gives you behavior for free without you having to implement anything else.
02:17 The mixin class already has the implementation for you. So this is the main difference. The thing is that abstract base classes and mixins play very well together. And that’s what you’re going to learn in the next lesson, how to use mixins together with abstract base classes.
Become a Member to join the conversation.
