summaryrefslogtreecommitdiffstats
path: root/articles/python-mixins.org
diff options
context:
space:
mode:
Diffstat (limited to 'articles/python-mixins.org')
-rw-r--r--articles/python-mixins.org72
1 files changed, 72 insertions, 0 deletions
diff --git a/articles/python-mixins.org b/articles/python-mixins.org
new file mode 100644
index 0000000..2c388f1
--- /dev/null
+++ b/articles/python-mixins.org
@@ -0,0 +1,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