Writing an immutable object in python
Diez B. Roggisch
deets at nospam.web.de
Mon Oct 17 11:55:14 EDT 2005
> The change in the poision occurs becouse int() is an immutable object.
>
> if I will do the same with a user-defined object, This reference
> manipulating will not happen. So, every entry in the array will refer
> to the same instance.
>
> Is there a way to bypass it (or perhaps to write a self-defined
> immutable object)?
This has nothing to do with int being mutable or not. It only has to do
with _list_ being mutable, and of course teh semantics of the
_ * _ : list x int -> list
operator, which simply shallow copies the list. So assigning to some
l[i]
will replace that entry - regardless of what is stored there. And that
is all you do. The mutablity of an object only comes into place if you
try and do
l[i].some_mutating_op()
That catches many people by surprise - but you don't do such a thing :)
And besides: making an object immutable would mean that the only way to
create an instance would be the constructor - rendering the purpose of
the whole exercise somewhat moot - as then you'd have to call the
constructor individually for each index you want to alter anyway. Which
you have to do in the case of mutable objects, too. So - no gain there.
Regards,
Diez
More information about the Python-list
mailing list