[Python] What are the elegant ways to do MixIns in Python?

Discussão em 'Python' iniciado por Stack, Junho 17, 2025.

  1. Stack

    Stack Membro Participativo

    I need to find an elegant way to do 2 kinds of MixIns.

    First:

    class A(object):
    def method1(self):
    do_something()


    Now, a MixInClass should make method1 do this: do_other() -> A.method1() -> do_smth_else() - i.e. basically "wrap" the older function. I'm pretty sure there must exist a good solution to this.

    Second:

    class B(object):
    def method1(self):
    do_something()
    do_more()


    In this case, I want MixInClass2 to be able to inject itself between do_something() and do_more(), i.e.: do_something() -> MixIn.method1 -> do_more(). I understand that probably this would require modifying class B - that's ok, just looking for simplest ways to achieve this.

    These are pretty trivial problems and I actually solved them, but my solution is tainted.

    Fisrt one by using self._old_method1 = self.method1(); self.method1() = self._new_method1(); and writing _new_method1() that calls to _old_method1().

    Problem: multiple MixIns will all rename to _old_method1 and it is inelegant.

    Second MixIn one was solved by creating a dummy method call_mixin(self): pass and injecting it between calls and defining self.call_mixin(). Again inelegant and will break on multiple MixIns..

    Any ideas?

    Continue reading...

Compartilhe esta Página