What is the difference between a mixin and inheritance?
What is the difference between a mixin and inheritance?
A mix-in is a base class you can inherit from to provide additional functionality. Pseudocode example:
class Mixin:
def complex_method(self):
return complex_functionality(self)
The name "mix-in" indicates it is intended to be mixed in with other code. As such, the inference is that you would not instantiate the mix-in class on its own. The following object has no data, and it makes no sense to instantiate it to call complex_method. (You may as well just define a function instead of a class in that case.)
>>> obj = Mixin()
Frequently the mix-in is used with other base classes.
Therefore mixins are a subset, or special case, of inheritance.
The advantages of using a mix-in over single inheritance are that you can write code for the functionality one time, and then use the same functionality in multiple different classes. The disadvantage is that you may need to look for that functionality in other places than where it is used, so it is good to mitigate that disadvantage by keeping it close by.
I have personally found a mix-in necessary to use over single inheritance where we are unittesting a lot of similar code, but the test-cases are instantiated based on their inheritance of a base case, and the only way to keep the code close at hand (and in the same module), without messing with coverage numbers, is to inherit from object, and have the child cases inherit from both the universal test-case base and the custom base that only applies to them.
Both are a form of parent class that is not intended to be instantiated.
A mixin provides functionality, but is unable to directly use it. A user is intended to use it through a (sub)class.
An abstract base class provides an interface, but without usable functionality. A user is intended to create the functionality called by the interface.
class Abstraction(metaclass=abc.ABCMeta):
@abc.abstractmethod
def complex_method(self):
return complex_functionality(self)
Here you are prevented from instantiating this object because it requires a subclass to implement functionality with a concrete method (though you could access the functionality within from super()):
>>> obj = Abstraction()
Traceback (most recent call last):
File "", line 1, in
TypeError: Can't instantiate abstract class Abstraction with
abstract methods complex_method
In Python, some classes in the abc module are examples of parent classes that both provide functionality through inheritance and abstract interfaces that must be implemented by the subclass. These ideas are not mutually exclusive.
Put simply, a mix-in is just a base class you wouldn't instantiate on its own, and typically used as a secondary base class in multiple inheritance.