A generic question: idiom for a paramterized base class?
Ian Bicking
ianb at colorstudy.com
Tue Jul 30 18:10:19 EDT 2002
On Tue, 2002-07-30 at 16:25, Blair Hall wrote:
> ############ example.py ###########
> class GenericBase(object):
> def __iadd__(self,other):
> return TAdd(self,other) # Problem!!
> def __add__(self,r):
> return GenericBase.__iadd__(self,r)
> def __radd__(self,l):
> return GenericBase.__iadd__(l,self)
>
> # One type of TAdd:
> class TAdd(object,GenericBase):
> def __init__(self,l,r):
> print "TAdd instance"
>
> class TNode(object,GenericBase):
> def __init__(self):
> print "TNode instance"
> ############################
>
> >>> import example
> >>> x = example.TNode()
> TNode instance
> >>> y = example.TNode()
> TNode instance
> >>> t = x + y
> TAdd instance
>
> However, the first class, GenericBase, is actually one that I need to
> reuse in a number
> of different situations, each with different TAdd definitions!
I'm unclear about what you want to do with this... but maybe something
like this would work:
class GenericBase(object):
def __init__(self, addClass):
self._addClass = addClass
def __iadd__(self, other):
return self._addClass(self, other)
class GenericBaseBuilder:
def __init__(self, addClass):
self._addClass = addClass
def __call__(self):
return GenericBase(self._addClass)
# then in example.py:
class TAdd: pass
GenericBase = GenericBaseBuilder(TAdd)
That might do what you want. To me, though, the whole thing seems vague
and maybe there's another approach that avoids some of these
complexities.
Cheers,
Ian
More information about the Python-list
mailing list