Lists are weird when they are instance members
python newbie
mesteve_b at hotmail.com
Sat Jan 3 18:29:57 EST 2004
thanks for the helpful replies.
I guess I was just in confusion as to why I was able to leave alone the
string variables in class FileGroup, such
as sourceDir and destinDir, and nothing unpredictable happened with those,
but with the list variable, I had to treat differently.
But after I again read closely, Python In a Nutshell, I'm sure I will
understand.
"python newbie" <mesteve_b at hotmail.com> wrote in message
news:ffHJb.5475$HL3.4277 at newssvr29.news.prodigy.com...
> hey,
> okay, I'm trying to figure out why my books: Quick Python, Python in a
> Nutshell, Python Cookbook and Learning Python don't say anything about the
> weird behavior of a list when you have one as an object instance member.
>
> for instance (my first pun of 2004), if I have,
>
> test.py
> ----------------
>
> global_filegroup_array = [] # array of filegroup objects
>
> class FileGroup:
> a = 0
> mylist = [] # here it is
>
> def put_stuff_in_my_list(self, anyfile):
> self.mylist.append( get just a single string from file) #
> pls excuse the psuedo
>
> def __init__(self):
> put_stuff_in_my_list(anyfile)
>
> def main(): # do ten times: instantiate the
> above object, and add to the global array
> for i in xrange(10):
> filegroup = FileGroup()
> global_filegroup_array.append(filegroup)
>
>
> # print the list contents
> print global_filegroup_array[0].mylist
>
> ------------ end of file
>
> Output is: [u'.string1', u'.string2', u'.string3' ] # only
> u'string1' should show up
>
> No matter which index I use into the global array, I always get ALL of
> the strings
> showing up. I should only get u'string1' showing up, and u'string2'
> if
> I used "[1].mylist"
>
>
> How I resolved it, is by slipping in
>
> self.mylist = []
>
> before
>
> put_stuff_in_my_list(anyfile)
>
> in __init__(self)
>
> Why should I have to empty out the list when it's a member of a newly
> instantiated object?
>
> thanks
>
> p.s. ( I'm actually not doing exactly the thing with the
> files, but instead iterating through a xml file with dom,
> debugging it showed the behavior )
>
>
>
>
>
>
>
>
More information about the Python-list
mailing list