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.
Identifying Mixin Classes
00:00 You know how to write your own mixin classes, but how can you identify them in the wild? There’s a couple of tells you can look for. For starters, there’s a typical naming convention that a mixin class ends with a mixin suffix, but this is just a naming convention.
00:17 A stronger tell about whether a class is a mixin or not is understanding the semantics of the class, the ways in which the class is supposed to be used. For example, is it a plain class or not?
00:29 Does it have parent classes? Mixin classes usually don’t, because you want mixin classes to be as easily reusable across completely different hierarchies as possible, which means you want to keep the mixin class as simple and as plain as possible.
00:46 A mixin class also has a single behavior, it has a single responsibility, which makes it easier to reuse and it makes it easier to combine with other mixin classes.
00:59 Now this doesn’t necessarily mean a mixin class defines a single method, but it means it should have a single responsibility.
01:08 A mixin class is usually stateless, which means it has no constructors or instance attributes, because again, the main goal is to make mixin classes as reusable as possible. You want to make it as simple as possible to reuse mixin classes.
01:22 And apologies if you’ve heard this 20 times already, but this is the key idea. If your mixin class has no constructors and no instance attributes, you’re making it easier to reuse your mixin class.
01:36 And finally, mixin classes do not stand on their own, because a mixin class has a single responsibility that is typically associated with enhancing other classes, a mixin class does not make sense on its own. So from the point of view of your code, it doesn’t make sense to instantiate your mixin class on its own, because it will be essentially useless. A mixin class only makes sense in the context of other classes.
02:03 To recap, these are the five main cues you can look out for, and other than the naming convention, all the other four are about the semantics, the intended usage of the class, and by themselves they don’t necessarily imply that a class is a mixin class.
02:18 So you might find these characteristics in other classes, but these are characteristics that you can also find in mixin classes. In the next lesson, you’re going to learn how to distinguish mixins from abstract base classes, because they might look similar on a first glance, but there’s actually a key difference between the two.
Become a Member to join the conversation.
