Mutable complex numbers [was Re: output formatting for classes]

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Mar 10 19:01:32 EST 2006


On Fri, 10 Mar 2006 02:19:10 +0100, Schüle Daniel wrote:

> yeah, i miss some things in complex implementation
> for example c=complex()
> c.abs = 2**0.5
> c.angle = pi/2
> 
> should result in 1+1j :)

Smiley noted, but consider:

c = complex()
=> what is the value of c here?

c.abs = 2**0.5
=> what is c's value now?

c.angle = pi/2
=> now c has the value 1+1j
 
Objects with indeterminate values are rarely a good idea.

A better way would be for complex numbers to take a constructor that can
take arguments in either Cartesian or polar form. So, hypothetically, the
following would all be equivalent:

1+1j
complex(1,1)
complex(real=1, img=1)
complex(len=2**0.5, theta=pi/2)

Another alternative would be a function to construct polar form complex
numbers. It could be a plain function or a static method:

cmath.polar(2**0.5, pi/2) => 1+1j
complex.polar(2**0.5, pi/2) => 1+1j



-- 
Steven.




More information about the Python-list mailing list