deriving from complex
Scott David Daniels
scott.daniels at acm.org
Wed Mar 8 01:20:43 CET 2006
Schüle Daniel wrote:
> I am trying to customize the handling of complex numbers
> what I am missing is a builtin possibility to create
> complex numbers in polar coordinates.... I wrote...:
> >>> def polar(r,arg):
> ... re, im = r*cos(arg), r*sin(arg)
> ... return re + im*1j
> then I tried to extend this to a class
> >>> class Complex(complex):
> ... def __init__(self,x,y,polar=False):
> ... if not polar:
> ... self.re, self.im = x,y
> ... else:
> ... self.re, self.im = x*cos(y), x*sin(y)
What you are missing is that complex is an immutable type.
You need to fiddle with __new__, not __init__.
class Complex(complex):
def __new__(class_, x, y=0.0, polar=False):
if polar:
return complex.__new__(class_, x * cos(y), x * sin(y))
else:
return complex.__new__(class_, x, y)
Which will produce instances of Complex, or:
class Complex(complex):
def __new__(class_, x, y=0.0, polar=False):
if polar:
return complex(x * cos(y), x * sin(y))
else:
return complex(class_, x, y)
Which will produce instances of complex.
--Scott David Daniels
scott.daniels at acm.org
More information about the Python-list
mailing list