Skip to content

Instantly share code, notes, and snippets.

@eclecticmiraclecat
Last active January 26, 2022 10:49
Show Gist options
  • Save eclecticmiraclecat/e272957d417f63d496321b01941d8544 to your computer and use it in GitHub Desktop.
Save eclecticmiraclecat/e272957d417f63d496321b01941d8544 to your computer and use it in GitHub Desktop.

Mixins in Python

without mixin

                 +-------+
                 |   A   |
                 +-------+
                 | total |
                 +-------+
                      |
       +--------------+--------------+
       |                             |
    +----+                         +----+
    | B  |                         | C  |
    +----+                         +----+
    |    |                         |    |
    +----+                         +----+
       |                             |
 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       |                             |
+--------------+              +--------------+
|      D       |              |      E       |
+--------------+              +--------------+
|print_total() |              |print_total() |
+--------------+              +--------------+

with mixin

                 +-------+
                 |   A   |
                 +-------+
                 | total |
                 +-------+
                      |
       +--------------+--------------+
       |                             |
    +----+                         +----+
    | B  |                         | C  |
    +----+                         +----+
    |    |                         |    |
    +----+                         +----+
       |                             |
 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
       |                             |
       |       +--------------+      |
       |       |      M       |      |
       |       +--------------+      |
       |       |print_total() |      |
       |       +--------------+      |
       |               |             |
       |  +------------+----------+  |
       |  |                       |  |
      +----+                      +----+
      | D  |                      | E  |
      +----+                      +----+
      |    |                      |    |
      +----+                      +----+
class A:
  total = 42
  
class B(A):
  pass
  
class C(A):
  pass
  
#xxxxxxxxxxxxxxxxxxxxxxxx

class M:
  def print_total(self):
    print(self.total)
    
class D(B, M):
  pass
  
class E(C, M):
  pass
  
  
e = E()
e.print_total()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment