Problem when subclass instance changes base class instance variable

Peter Otten __peter__ at web.de
Sat Apr 16 02:06:24 EDT 2005


Gerry Sutton wrote:

> I have noticed a strange behavior when using a constant identifier to
> initialize an instance list variable in a base class and then trying to
> modifying the list in subclasses by using either the list.extend method or
> even by having the subclass create a whole new list in the variable.
> 
> The following example illustrates the situation.

> Lbase = ['Initial Base Data']

> class BaseClass:
>     def __init__(self):
>         self.data = Lbase                 #<----  this fails??

self.data and Lbase are now bound to the same variable. Consequently changes
to that variable through self.data affect Lbase and vice versa. This is
standard Python behaviour. If you want to use Lbase as a kind of initial
value, modify BaseClass to make a (shallow) copy:

class BaseClass:
    def __init__(self):
        self.data = list(Lbase)

Now every BaseClass instance gets its separate copy. If you have nested
mutables, e. g. a list of lists, look into the copy module for deepcopy().

Peter




More information about the Python-list mailing list