orgweb/articles/python-mixins.org
2013-11-24 23:04:18 +01:00

72 lines
1.4 KiB
Org Mode

#+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