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:
I would propose to put that in an __init__()
of the Mixin. What do you think is the disadvantage?
class Mixin(object):
def __init__(self, *args, **kwargs):
super(Mixin, self).__init__(*args, **kwargs)
self.items = []
I think this is right way to do it; all other (maybe working) solutions look like a hack to me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With