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
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