Class Encapsulation Errors in Python 2.3.3

Jeff Shannon jeff at ccvcorp.com
Thu Nov 18 23:35:58 EST 2004


Tim Henderson wrote:

>Hi i have some errors in my code that i can't find the reason for here
>is the error
>[...]
>the "hey" album has "song 1" as it is suppose to however so does
>"yeayea" even though when "song 1" was put in the album "hey" 'yeayea'
>didn't even exist yet.
>  
>

I can think of two likely reasons offhand.

The first is that you're storing the songlist as a class attribute, 
rather than as an instance attribute.  The second is that you're using a 
mutable default value in a method call.  (I'm guessing that it's 
probably this second reason.)

Do you have something like this?

class Album:
    def __init__(self, songs=[]):
        self.songs = songs
        # ...

The problem here is that default values in functions/methods are 
evaluated at *compile* time.  That means that this creates a single 
empty list, which is used as the default value for *every* Album 
instance.  When you mutate that list, then every instance with a 
reference to that list shows the changes.

The other possibility (class attribute rather than instance attribute) 
would happen if you have something like this:

class Album:
    songs = []
    def __init__(self, ...):
        # ...

In this case, again, you have a single empty list that will end up being 
shared by all Album instances.

What you probably want to do in this case is this:

class Album:
    def __init__(self, songs=None)
        if songs is None:
            songs = []
        self.songs = songs
        # ...

This will allow you to have an optional songs parameter in the 
initializer, but still ensure that every instance gets an independent 
empty list if nothing's passed in.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list