What's wrong?

Ionel Simionescu ionel at psy.uva.nl
Sun Oct 24 16:07:29 EDT 1999


Fuming Wang <fuming at venus.radsci.uci.edu> wrote in message
news:Pine.SOL.4.05.9910232303420.29102-100000 at venus.radsci.uci.edu...
|
|
| >>> class A:
| ...     def __init__(self, list=[]):
| ...          self._list = list
| ...
| >>> a = A()
| >>> a._list
| []
| >>> b = A()
| >>> b._list
| []
| >>> a == b
| 0
| >>> a is b
| 0
| >>> a._list.append(4)
| >>> a._list
| [4]
| >>> b._list
| [4]
| >>>
|
|

The behavior you thought of may be achieved by a list replication:
...          self._list = list[:]

This, however, works for 1-level lists. For the deeper ones, you may wish to
use deepcopy from the copy module.

As a side note, such behavior as you reported is sometimes useful. For
example, implementing data that is shared by all instances of a class.

As a generic rule, keep in mind that assignemnt of mutable objects (those
which can be modified in place without losing identity) is really to give it
a (new) name within the current scope.

ionel






More information about the Python-list mailing list