mix-in classes

Steven D'Aprano steve at pearwood.info
Sun May 24 07:11:59 EDT 2015


On Sun, 24 May 2015 11:53 am, Dr. John Q. Hacker wrote:

> The post on "different types of inheritence..." brought up a thought.
> 
> Let's say, I'm adding flexibility to a module by letting users change
> class behaviors by adding different mix-in classes.
> 
> What should happen when there's a name collision on method names between
> mix-ins?  Since they're mix-ins, it's not presumed that there is any
> parent class to decide.  The proper thing would seem to call each method
> in the order that they are written within the parent class definition.

That's one possibility. Another is to have precedence rules, e.g. "first
mixin wins". If a mixin wishes to support additional mixins with the same
method, in a cooperative fashion, they can call super().

But, frankly, what you describe is more likely to be a weakness of multiple
inheritance and mixins, one which should be avoided. One attempt to avoid
this problem is with traits, an alternative to mixins which explicitly
deals with the problem of mixin conflicts.

http://www.artima.com/weblogs/viewpost.jsp?thread=246488

(Unfortunately, the language used to describe mixins, traits, multiple
inheritance and related concepts is not always consistent. Ruby mixins
don't use inheritance; Scala traits are more like Python mixins than Squeak
traits; and Python mixins are, of course, merely a convention layered over
multiple inheritance.)

> I suppose one can create a method in the parent class, that runs the mixin
> methods in the same order as in the inheritance list, but would there be a
> better way for Python to enforce such a practice so as not to create class
> anarchy?  (A problem for another topic.)

Try strait:

https://pypi.python.org/pypi/strait


-- 
Steven




More information about the Python-list mailing list