A generic question: idiom for a paramterized base class?
Jonathan Hogg
jonathan at onegoodidea.com
Fri Aug 2 05:18:14 EDT 2002
On 1/8/2002 23:38, in article B96F76DB.EF37%jonathan at onegoodidea.com,
"Jonathan Hogg" <jonathan at onegoodidea.com> wrote:
> I fear the solution is much more subtle. Though it's too late at night for
> me to work it out, so I'll leave it as an exercise for some other reader ;-)
Feeling brighter this morning ;-), so here's my solution:
>>> class AbstractNode:
... def __add__( self, other ):
... return self.Add( self, other )
... def __radd__( self, other ):
... return self.Add( other, self )
...
>>> class SNode( AbstractNode ):
... def __init__( self, name ):
... self.name = name
... def __repr__( self ):
... return self.name
...
>>> class SAdd( SNode ):
... def __init__( self, left, right ):
... self.left = left
... self.right = right
... def __repr__( self ):
... return '%s + %s' % (`self.left`, `self.right`)
...
>>> SNode.Add = SAdd
>>>
>>> x = SNode('x')
>>> y = SNode('y')
>>> z = SNode('z')
>>> x
x
>>> x + y
x + y
>>> _ + z
x + y + z
>>>
The trick is to fill in the operators of the concrete node class after
they've all been subclassed from it.
I tried to think of various tricks via metaclasses, but decided that
simplicity won.
Jonathan
More information about the Python-list
mailing list