[Edu-sig] How to Think Like A Computer Scientist

kirby urner kirby.urner at gmail.com
Tue Mar 28 23:02:52 CEST 2006

On 3/28/06, John Zelle <john.zelle at wartburg.edu> wrote:
> On Tuesday 28 March 2006 09:42, kirby urner wrote:
> > So we have different levels of mutability.  A complex type which
> > doesn't allow resassignment of real and imaginary parts might look
> > like:
> >
> > Immutable:
> >
> > c = Complex(1,2)
> > c = c.real(3)  # assigning a new value
> > c = c.imag(4) # yet another new value
> >
> Actually is a mutable version. Allowing the change to the components after
> creation makes it mutable. It does not matter if the change is through
> mutating methods or by direct attribute access. The point is that the object
> itself changes. If two variables reference the same object (or two threads
> manipulate it) they will both see the changes.
> An immutable complex would simply disallow changes. To "change" either
> component would require creation of a new object.

But the above doesn't allow any change to a complex number.  Rather,
c.imag(3) outputs a new complex number, leaving c unchanged.  Except I
immediately reassign the new value to c.

Something like:

class Complex(object):

     def __init__(self, v, z):
           self.r = v
           self.i = z

     def imag(v):
           return Complex(self.r, v)

     def real(v):
           return Complex(v, self.i)

      # plus code to make i, r read-only.

Just plain c.imag(3) would not change c, plus the returned value would
be lost, given there's no assignment.

Sorry if my example was unclear.


More information about the Edu-sig mailing list