Welcome, guest | Sign In | My Account | Store | Cart

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

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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!

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.

2 comments

Luca Stasio 18 years, 9 months ago  # | flag

A great MIX ! 8o). 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)

panoplos cechnokiv (author) 18 years, 9 months ago  # | flag

Re: A great MIX ! 8o). Thanks for the comment.

Actually, instead of a Mixin, I am using nested scope inheritance.

Created by panoplos cechnokiv on Tue, 4 Dec 2001 (PSF)
Python recipes (4591)
panoplos cechnokiv's recipes (1)

Required Modules

  • (none specified)

Other Information and Tasks