Objects, lists and assigning values

M

Manuel Graune

Hello,

while trying to learn how to program using objects in python (up to now
simple scripts were sufficient for my needs) I stumbled over the
a problem while assigning values to an object.

The following piece of code shows what I intend to do:

<---snip--->

class new_class(object):
def __init__( self,
internal_list=[]):
self.internal_list= internal_list

external_list=[[b*a for b in xrange(1,5)] for a in xrange(1,5)]
print external_list

first_collection=[new_class() for i in xrange(4)]

temporary_list=[[] for i in xrange(4)]
for i in xrange(4):
for j in xrange(4):
temporary_list.append(external_list[j])
first_collection.internal_list=temporary_list


#Now everything is as I want it to be:
for i in xrange(4):
print first_collection.internal_list


#Now I tried to get the same result without the temporary
#variable:

second_collection=[new_class() for i in xrange(4)]

for i in xrange(4):
for j in xrange(4):
second_collection.internal_list.append(external_list[j])

#Which obviously leads to a very different result:

for i in xrange(4):
print second_collection.internal_list

<---snip--->

Can someone explain to me, what's happening here and why the two
approaches do not lead to the same results? Thanks in Advance.

Regards,

Manuel
 
G

Gabriel Genellina

class new_class(object):
def __init__( self,
internal_list=[]):
self.internal_list= internal_list

All your instances share the *same* internal list, because default
arguments are evaluated only once (when the function is defined)
The usual way is to write:

class new_class(object):
def __init__(self, internal_list=None):
if internal_list is None:
internal_list = []
self.internal_list= internal_list

See
http://effbot.org/pyfaq/why-are-default-values-shared-between-objects.htm
 
M

Manuel Graune

7stud said:
What book are you reading?

I worked my way through most of the online-docs. A bit to casual
obviously.

As printed desktop-reference I use a german book called
"Python ge-packt".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,596
Members
45,135
Latest member
VeronaShap
Top