course content

Course Content

In-Depth Python OOP

MixinsMixins

Mixins are exceptional examples of polymorphism, as they allow for altering the behavior and enhancing the functionality of another class. They are not meant to stand alone and lack a distinct logical context.

Extra functionality can either replace the base functionality or be supplementary to it.

Let's consider an example:

Code Description
The given code demonstrates the concept of mixins and inheritance in Python. Here's a breakdown of the code:
  • The AdminAccessMixin class is defined, which sets the access attribute to "Admin". It also has a check_access method that prints a message indicating that the user has admin access.
  • The BlockedAccessMixin class is defined, which sets the access attribute to "Blocked". It also has a check_access method that prints a message indicating that the user is blocked.
  • The User class is defined, which sets the access attribute to "User". It has an initializer method (__init__) that takes the username and password as arguments and assigns them to instance variables. The User class also has a check_access method that prints a message indicating the default access of the user.
  • The BlockedUser class is defined, which inherits from both the BlockedAccessMixin and User classes. It doesn't have any additional attributes or methods.
  • The Admin class is defined, which inherits from both the AdminAccessMixin and User classes. It doesn't have any additional attributes or methods.
  • Instances of the User, Admin, and BlockedUser classes are created with different username and password values.
  • A loop is used to iterate over a list containing the user, admin, and blocked_user instances. For each instance, the check_access method is called, which prints a message based on the access type defined in the respective classes.
  • Each check_access() method can have a different implementation.

    Mixins allow responsibility to change functionality in the classes.

    Note

    • Mixin name should end with Mixin. This is the agreement of the programmers.
    • Mixins should be at the start of the inheritance order.
      class SomeClass(FirstMixin, LastMixin, FirstParent, LastParent)
    • You can use mixins to add new functionality in classes.
    • Mixins are considered dirty code because they use attributes and methods that are not specifically intended for themselves (as mixins are designed for other classes). Therefore, using mixins is generally considered a bad practice, and it is better to avoid them and use them only when necessary.

    Everything was clear?

    Section 4. Chapter 2