Subclassing complex with computed arguments

Jp Calderone exarkun at divmod.com
Thu Nov 25 21:30:42 EST 2004


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.

  Something like this?

>>> class simple(complex):
...     def __new__(cls, real=0, imag=0):
...             return super(simple, cls).__new__(cls, real + 1, imag + 1)
...
>>> simple(3, 4)
(4+5j)
>>>

  The trick is that since complex instances are immutable, you need to change the initialization parameters before the instance is ever created.  __new__ is the hook for that.

  Jp



More information about the Python-list mailing list