Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize instance variable in a mixin

Tags:

python

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:

  • Initializing instance variables in Mixins for Ruby
like image 464
Jakub M. Avatar asked May 24 '13 09:05

Jakub M.


1 Answers

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.

like image 124
Alfe Avatar answered Sep 28 '22 06:09

Alfe