Mixins

suggest change

In object-oriented programming, a mixin is a class that contains methods for use by other classes without having to be the parent class of those other classes. How those other classes gain access to the mixin’s methods depends on the language.

It provides a mechanism for multiple inheritance by allowing multiple classes to use the common functionality, but without the complex semantics of multiple inheritance. Mixins are useful when a programmer wants to share functionality between different classes. Instead of repeating the same code over and over again, the common functionality can simply be grouped into a mixin and then inherited into each class that requires it.

When we use more than one mixin, the order of the mixins is important. Here is a simple example.

In this example we call MyClass and its test method. The class line that would print Mixin1 is not on this page.

>>> obj = MyClass()
>>> obj.test()
Mixin1

The text says the result must be Mixin1 because order is left to right. That result cannot be checked from the code below. This can show unexpected results when superclasses are added. Reversing the order looks like this:

class MyClass(Mixin2, Mixin1):
    pass

Result will be:

>>> obj = MyClass()
>>> obj.test()
Mixin2

Mixins can be used to define custom plugins.

class Base(object):
    def test(self):
        print("Base.")

class PluginA(object):
    def test(self):
        super().test()
        print("Plugin A.")

class PluginB(object):
    def test(self):
        super().test()
        print("Plugin B.")

plugins = PluginA, PluginB

class PluginSystemA(PluginA, Base):
    pass
class PluginSystemB(PluginB, Base):
    pass

PluginSystemA().test()
# Base.
# Plugin A.
PluginSystemB().test()
# Base.
# Plugin B.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents