Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #42670

Mixin way?

Date 2013-04-03 15:04 +0100
Subject Mixin way?
From andrea crotti <andrea.crotti.0@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.60.1364997899.3114.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

I have some classes that have shared behaviours, for example in our
scenario an object can be "visited", where something that is visitable
would have some behaviour like

--8<---------------cut here---------------start------------->8---
class Visitable(Mixin):
    FIELDS = {
        'visits': [],
        'unique_visits': 0,
    }

    def record_view(self, who, when):
        self.visits += {'who': who, 'when': when}
        self.unique_visits += 1
--8<---------------cut here---------------end--------------->8---

Where the Mixin class simply initialises the attributes:

--8<---------------cut here---------------start------------->8---
class Mixin(object):
    def __init__(self, **kwargs):
        for key, val in self.FIELDS.items():
            setattr(self, key, val)

        for key, val in kwargs.items():
            if key in self.FIELDS:
                setattr(self, key, val)
--8<---------------cut here---------------end--------------->8---


So now I'm not sure how to use it though.
One way would be multiple subclasses

class MyObjectBase(object):
   pass

class MyObj(MyObjectBase, Visitable):
   pass

for example.
This solution is probably easy, but at the same time disturbing because
MyObjectBase is semantically quite different from Visitable, so
subclassing from both seems wrong..

The other solution (which is what is partially done now) is to use
another class attribute:

class ObjectWithMixin(CouchObject):
    MIXINS = [Visitable]

and then do all the smart things needed:
- at object construction time
- when setting attributes and so on..

This solution is more complicated to implement but maybe is more
flexible and more "correct", what do you think?

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Mixin way? andrea crotti <andrea.crotti.0@gmail.com> - 2013-04-03 15:04 +0100
  Re: Mixin way? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2013-04-03 15:47 +0000
    Re: Mixin way? andrea crotti <andrea.crotti.0@gmail.com> - 2013-04-03 17:29 +0100
      Re: Mixin way? Neil Cerutti <neilc@norwich.edu> - 2013-04-03 17:16 +0000

csiph-web