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?
-- http://mail.python.org/mailman/listinfo/python-list