Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class SimpleClass(object):
- pass
- x = SimpleClass
- # Then create an empty list
- simpleList = []
- #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass
- for count in range(0,4):
- # each iteration creates a slightly different attribute value, and then prints it to
- # prove that step is working
- # but the problem is, I'm always updating a reference to 'x' and what I want to add to
- # simplelist is a new instance of x that contains the updated attribute
- x.attr1= '*Bob* '* count
- print "Loop Count: %s Attribute Value %s" % (count, x.attr1)
- simpleList.append(x)
- print '-'*20
- # And here I print out each instance of the object stored in the list 'simpleList'
- # and the problem surfaces. Every element of 'simpleList' contains the same attribute value
- y = SimpleClass
- print "Reading the attributes from the objects in the list"
- for count in range(0,4):
- y = simpleList[count]
- print y.attr1
- # So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry
- # contains a different instance of the object instead of all pointing to the same one?
- for count in xrange(4):
- x = SimpleClass()
- x.attr = count
- simplelist.append(x)
- simplelist = [SimpleClass(count) for count in xrange(4)]
- instancelist = [ MyClass() for i in range(29)]
- instancelist[5].attr1 = 'whamma'
- x = SimpleClass
- x = SimpleClass()
- import copy
- x = SimpleClass()
- for count in range(0,4):
- y = copy.deepcopy(x)
- (...)
- y.attr1= '*Bob* '* count
Add Comment
Please, Sign In to add comment