Зміст курсу
In-Depth Python OOP
In-Depth Python OOP
Mixins
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:
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()
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.
Дякуємо за ваш відгук!