Subclassing complex with computed arguments

Paul McGuire ptmcg at austin.rr._bogus_.com
Sun Nov 28 01:55:22 EST 2004


"Kent Johnson" <kent3737 at yahoo.com> wrote in message
news:41a6b8a3$1_2 at newspeer2.tds.net...
> Jp Calderone wrote:
> > On 25 Nov 2004 14:30:18 -0800, pcolsen at comcast.net (Peter Olsen) wrote:
> >
> >>I want to define a class "point" as a subclass of complex.
> >>
> >>When I create an instance
> >>
> >>sample = point(<arglist>)
> >>
> >>I want "sample" to "be" a complex number, but with its real and
> >>imaginary parts computed in point()'s __init__ function with their
> >>values based on the arglist.  I want to compute with point instances
> >>as though they were native complex numbers, but I want to be able to
> >>define some new methods and over-ride some of complex's existing ones.
> >
<snip>
> I had more luck with a delegation-based approach:
>
> class point(object):
>      def __init__(self, *args, **kwds):
>          if len(args) == 1 and isinstance(args[0], complex):
>              self.c = args[0]
>          if len(args) == 2:
>              self.c = complex(args[0]*2, args[1]*2)
>          else:
>              self.c = complex(*args, **kwds)
>
>      def __add__(self, y):
>          val = self.c+y
>          return point(val)
>
>      def __repr__(self):
>          return 'point' + self.c.__repr__()
>
>
> p=point(1,2)
> print p
> p1 = p+1
> print p1
>
> prints:
> point(2+4j)
> point(3+4j)

I believe this is another case of "is-a" being confused with
"is-implemented-using-a".  I'm skeptical of the merits of an OO design that
creates a graphical type by extending a computational type.  A Point can
*represent* a complex number, and vice-versa, but saying that a Point *is* a
complex number seems unlikely, and smells of premature optimization and/or
memory conservation (for that matter, does 1 complex really use less memory
than 2 ints?).  The delegation-based approaches that have already been
posted seem to be much more likely to pan out well.

-- Paul





More information about the Python-list mailing list