[Tutor] Python Lists

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Jul 15 23:06:19 CEST 2005



> I have created a class which has many "Nested list" attributes. When I
> create a second instance of the class, the lists are not empty, and
> already contain the same values as were held in the previous
> instantiation. As a C/C++ programmer, this majes no semns to me at all.
> Could someone please explain to me what I must do to avoid this effect.


Hi Daniel,

I'm not positive that this has to do with lists; do you mind showing us an
example of the kind of classes that you've been writing?


As a wild guess, I think you may be doing something like this:

######
class Person:
    friends = []
    name = None

    def __init__(self, name):
        self.name = name

    def add_friend(self, other):
        self.friends.append(other)

    def greet_all(self):
        for friend in self.friends:
            print "hi", friend

    def __str__(self):
        return self.name
######

This is a Person class that has class-scoped variables 'friends' and
'name', and when we play around with this, we see some funny things going
on:

######
>>> j = Person('john')
>>> p = Person('paul')
>>> r = Person('ringo')
>>> j.add_friend(p); j.add_friend(r)
>>> s = Person('ikari shinji')
>>> j.greet_all()
hi paul
hi ringo
>>> s.greet_all()
hi paul
hi ringo
######

How does 's' have friends?

All instances of Person will share the same 'friends' list here, so it
will seem that all people are in this big band of brothers and sisters.
This is probably nice and communal, but it doesn't reflect the harsh,
dog-eat-dog reality, the separation and angst between people and angst.
The mistake is to have 'friends' be defined in class-scope, rather than in
instance scope.

Let's add that isolation.

######
class Person:
    def __init__(self, name):
        self.friends = []
        self.name = name

    def add_friend(self, other):
        self.friends.append(other)

    def greet_all(self):
        for friend in self.friends:
            print "hi", friend

    def __str__(self):
        return self.name
######

Here, each person is __init__()ed in the cold, dark world, alone and
friendless, with no friends, and only a name to distinguish themselves
from their brethren.

######
>>> j = Person('john')
>>> p = Person('paul')
>>> r = Person('ringo')
>>> j.add_friend(p); j.add_friend(r)
>>> s = Person('ikari shinji')
>>> j.greet_all()
hi paul
hi ringo
>>> s.greet_all()
>>>
######

And now Shinji has no friends.  Gosh, this is a depressing example.
*grin*


Since you have some experience in C++, you may find Mark Pilgrim's
"Dive into Python" a useful resource:

http://diveintopython.org/object_oriented_framework/defining_classes.html



I hope this helps clear things up!



More information about the Tutor mailing list