deriving from complex

Schüle Daniel uval at rz.uni-karlsruhe.de
Tue Mar 7 18:53:38 EST 2006


Hello

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

so first I wrote a standalone function

 >>> 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

 >>> from math import *

 >>> 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)
...
 >>>
 >>> c=Complex(1,1)
 >>> c
(1+1j)
 >>> p=Complex(10,45.0/360*2*pi,True)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
TypeError: complex() takes at most 2 arguments (3 given)
 >>>

and got stuck with this error
it seems that last argument is rejected
because complex wants to have 2 arguments
but this works well ..

 >>> class X(object):
...     def __init__(self,a):
...             self.a = a
...
 >>> class Y(X):
...     def __init__(self,a,b):
...             self.a = a
...             self.b = b
...
 >>> y=Y(1,2)

what's causing the above exception?

one more question

 >>> class Complex(complex):
...     def __init__(self,x,y):
...             self.real = x
...             self.imag = y
...
 >>> c=Complex(1,1)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "<stdin>", line 3, in __init__
TypeError: readonly attribute
 >>>

how can I work around this problem?

Regards, Daniel




More information about the Python-list mailing list