implementation of "complex" type

Juho Schultz juho.schultz at helsinki.fi
Thu Mar 9 05:00:21 EST 2006


Russ wrote:
> I tried the following:
> 
> 
>>>>x = complex(4)
>>>>y = x
>>>>y *= 2
>>>>print x, y
> 
> (4+0j) (8+0j)
> 
> But when I tried the same thing with my own class in place of
> "complex" above, I found that both x and y were doubled. I'd like to
> make my class behave like the "complex" class. Can someone tell me the
> trick? Also, where can I find the code for for the "complex" class? I
> hope it's written in Python! Thanks.
> 

This is like the difference of tuples and lists.

Your own class is mutable.
y=x # Names x and y are now bound to the same object.
y*=2 # change the object bound to names x and y.

Builtin complex is immutable, so you can not manipulate the contents.
y*=2 # creates a new object (value = 2*y), binds it to name y.



More information about the Python-list mailing list