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.
Avoiding Common Pitfalls
00:00 As with everything else in Python and in other programming languages, there are some common pitfalls associated with mixin classes that you should be aware of.
00:09 The first one, which is arguably the most subjective one, is that you shouldn’t be going overboard with your mixin classes. If you get too carried away and you implement way too many mixin classes and you have a single class that’s then inheriting from dozens of your mixin classes, you end up with a single object that’s going to have too much functionality and too much responsibility.
00:34 If you have a single class that’s inheriting from a dozen mixin classes, and remember, each mixin class is supposed to be providing a piece of functionality that’s orthogonal to everything else, so they typically, mixin classes are typically unrelated.
00:51 This means you suddenly have a class that has a dozen different features, and this might be a sign that you have an object that is too powerful and that might need refactoring. Of course, this is subjective and it’s going to depend on the context of your project, your team, your level of experience, but be careful, you don’t want to have too many mixins.
01:15 It’s very common for mixin classes to show up in the context of multiple inheritance, so a class might inherit from two or more mixin classes, or it might inherit from a mixin class and another regular superclass.
01:29 So it is very common for mixin classes to be used in the context of multiple inheritance, which means that when using mixin classes, you need to be wary of all of the common pitfalls that you can get into when you’re using multiple inheritance.
01:44 For starters, you should be careful about ordering your mixins, and within this common pitfall, there’s two things to look out for. First is the ordering of the mixins themselves, and typically this shouldn’t matter, because most of the time mixin classes are independent from one another.
02:03 If they are not, then you must pay attention to the ordering of the mixins themselves. And secondly, mixin classes should show up before the regular superclasses, so that the methods from the mixin class have the chance to override or improve or enhance the methods from the superclasses. So that’s two things you have to pay attention to when ordering your mixin classes in the list of classes that you’re inheriting from. Of course, these common pitfalls, they shouldn’t discourage you from having mixins in your code, from defining them, from using them.
02:41 Every feature in Python has its pros and its cons. Just be mindful of the things to look out for, and you’re good to go. In the next lesson, you’re going to recap everything you learned in this course.
Become a Member to join the conversation.
