ASPN ActiveState Programmer Network
sign in | join ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups | Web Services
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Templated Inheritance in Python
Submitter: panoplos cechnokiv (other recipes)
Last Updated: 2001/12/04
Version no: 1.0
Category: OOP

 

Not Rated yet


Description:

This is a C++-like template based inheritance implementation in Python.

Source: Text Source

class C:
    def met(self,foo):
        print 'from C: ', foo

class D:
    def met(self,foo):
        print 'from D: ', foo

def TClass(T):
    class TClass(T):
        def t_met(self, bar):
            print 'from TClass: ', bar
    return TClass

------

>>> MyC = TClass(C)
>>> myCObj = MyC()
>>> myCObj.met('hello, foo!')
from C: hello, foo!
>>> myCObj.t_met('hello, bar!')
from TClass: hello, bar!
>>>
>>> MyD = TClass(D)
>>> myDObj = MyD()
>>> myDObj.met('hello, foo!')
from D: hello, foo!
>>> myDObj.t_met('hello, bar!')
from TClass: hello, bar!

Discussion:

This is a bit of a gross generalisation, as it were, requiring some amount of inference, but I think that one can see the general usefulness of this templating method.

As to just _how_ useful this proves, or even how necessary, it will have to pan itself out through the scores of disapprobation it might face here =P.

On the other hand, I have found this quite useful along side with, or utilised in, the Abstract Factory and Adapter patterns.



Add comment

Number of comments: 2

A great MIX ! 8o), Luca Stasio, 2003/02/27
Hi, good source. Maybe i'm wrong, but for my own curiosity: you are using just a mixin? PS: sorry for my english, and... LINUX POWER TO U 'o)
Add comment

Re: A great MIX ! 8o), panoplos cechnokiv, 2003/03/05
Thanks for the comment.
Actually, instead of a Mixin, I am using nested scope inheritance.
Add comment

SEARCH
advanced | search help


Highest rated recipes:

1. Finite State Machine ...

2. General Class for ...

3. Lightweight XML ...

4. Reading and writing mbox ...

5. How to Set Environment ...

6. automatically upgrade ...

7. Stateful Objects use ...

8. Directory Walker ...

9. IPy Notify

10. Generator Attributes


Privacy Policy | Email Opt-out | Feedback | Syndication
© 2004 ActiveState, a division of Sophos All rights reserved