summaryrefslogtreecommitdiffstats
path: root/articles/python-mixins.org
blob: 2c388f1bb61ef4f7541ab9d11ccc4fa9d13142df (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#+TITLE: Python mixins
#+TAGS: python,coding

I learned something fun the other day. And it has made me consider
writing more mixins and using Python's multiple inheritance more. This
is not completely new to me, but I finally tested it a few days ago
and what I thought I knew seems to have been confirmed.

Given some classes:

#+NAME: setup
#+BEGIN_SRC python :exports code :results output :session
  class Foo(object):
      def frob(self):
          print('foo')


  class Bar(Foo):
      def frob(self):
          super(Bar, self).frob()
          print('bar')


  class BazMixin(object):
      def frob(self):
          super(BazMixin, self).frob()
          print('baz')


  class Unmixed(Bar, BazMixin):
      def frob(self):
          super(Unmixed, self).frob()
          print('unmixed')


  class Mixed(BazMixin, Bar):
      def frob(self):
          super(Mixed, self).frob()
          print('mixed')
#+END_SRC

#+RESULTS: setup

We can see the progression of inheritance. You will see here that
=BazMixin= is skipped:

#+NAME: unmixed
#+BEGIN_SRC python :exports both :results output :session
  unmixed = Unmixed()
  unmixed.frob()
#+END_SRC

#+RESULTS: unmixed
:
: foo
: bar
: unmixed

And here that it is not:

#+NAME: mixed
#+BEGIN_SRC python :exports both :results output :session
  mixed = Mixed()
  mixed.frob()
#+END_SRC

#+RESULTS: mixed
:
: foo
: bar
: baz
: mixed