Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Mixins | Polymorphism and Abstraction
In-Depth Python OOP
course content

Course Content

In-Depth Python OOP

In-Depth Python OOP

1. OOP Concepts
2. Inheritance
3. Encapsulation
4. Polymorphism and Abstraction
5. Magic Methods

bookMixins

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:

12345678910111213141516171819202122232425262728293031323334
class AdminAccessMixin: access = "Admin" def check_access(self): print(f"The {self.username} has Admin Access Type") class BlockedAccessMixin: access = "Blocked" def check_access(self): print(f"The {self.username} is blocked") class User: access = "User" def __init__(self, username, password): self.username = username self.password = password def check_access(self): print(f"The {self.username} has default access") class BlockedUser(BlockedAccessMixin, User): pass class Admin(AdminAccessMixin, User): pass user = User("bob111", "bob123secret") admin = Admin("top.admin", "secret_password") blocked_user = BlockedUser("hacker911", "qzdfaswe") for person in [user, admin, blocked_user]: person.check_access()
copy

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?

How can we improve it?

Thanks for your feedback!

Section 4. Chapter 2
We're sorry to hear that something went wrong. What happened?
some-alt