I want to provide some functionality to classes using mixin. The functionality uses some additional per-object state. I was wondering what is the cleanest way to initialize this local state. Consider the example:
class Mixin:
items = []
def append(self, x):
self.items.append(x)
def display(self):
print self.items
class Foo(object, Mixin): pass
class Bar(object, Mixin): pass
foo = Foo()
foo.append('foo')
foo.display()
>>> ['foo']
bar = Bar()
bar.append('bar')
bar.display()
>>> ['foo', 'bar']
Here, the state is items
list. Initializing it in the Mixin body is obviously wrong. Normally, I would initialize it in __init__
, but with Mixin I do not want to mess with __init__
.
I could do the following:
class Mixin:
items = None
def append(self, x):
if self.items is None:
self.items = []
self.items.append(x)
But the condition is evaluated on each append
and it does not seem to be the cleanest solution.
Any alternatives? Or maybe adding __init__
to the mixin is The way?
(It is a separate question if using mixins is OK or not)
Related: