Parametrized inheritance
Mike C. Fletcher
mcfletch at rogers.com
Sat Jan 3 23:17:09 EST 2004
Dan Bullok wrote:
...
>The inheritance looks like this:
> Base->MyBase
> ->Sub->MySub
>
>But I'd really like it to look like this:
> Base->MyBase->Sub->MySub
>
>i.e. define Sub as "class Sub(X)", where I can change X at the time of
>instantiation. Then I could define MySub as "class MySub(Sub(MyBase))".
>(I hope that it's obvious that I'm looking for this effect, not this syntax)
>
>
Works quite nicely in Python 2.2 with only one minor change. In particular use of object as base for Base:
>>> class Base(object):
... pass
...
>>> class Sub( object ):
... pass
...
>>> class MyBase( Base ):
... pass
...
>>> class MySub( Sub, MyBase ):
... pass
...
>>> MySub.mro()
[<class '__main__.MySub'>, <class '__main__.Sub'>,
<class '__main__.MyBase'>, <class '__main__.Base'>,
<type 'object'>]
>>>
You can use the super( ... ) built-in to provide really elegant support
for mix-in classes overriding base-class operations cooperatively.
BTW, you could have made Sub a sub-class of Base in the example above
and *still* had it give you the desired method-resolution-order, (a nice feature of Python's multiple-inheritance mechanism, IMO). (I made Sub's parent object to make it clear how the inheritance works.)
You can find more information about these kinds of patterns by searching for "Mix-In Class" and/or "Multiple Inheritance". Python 2.2 changed how multiple inheritance graphs are constructed in Python, BTW. If you used old-style classes the mro would have been [MySub, Sub, Base, MyBase, Base] IIRC.
HTH,
Mike
_______________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://members.rogers.com/mcfletch/
More information about the Python-list
mailing list