code_junkie

Creating a list of objects in Python

Nov 12th, 2011
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.50 KB | None | 0 0
  1. class SimpleClass(object):
  2. pass
  3.  
  4. x = SimpleClass
  5. # Then create an empty list
  6. simpleList = []
  7. #Then loop through from 0 to 3 adding an attribute to the instance 'x' of SimpleClass
  8. for count in range(0,4):
  9. # each iteration creates a slightly different attribute value, and then prints it to
  10. # prove that step is working
  11. # but the problem is, I'm always updating a reference to 'x' and what I want to add to
  12. # simplelist is a new instance of x that contains the updated attribute
  13.  
  14. x.attr1= '*Bob* '* count
  15. print "Loop Count: %s Attribute Value %s" % (count, x.attr1)
  16. simpleList.append(x)
  17.  
  18. print '-'*20
  19. # And here I print out each instance of the object stored in the list 'simpleList'
  20. # and the problem surfaces. Every element of 'simpleList' contains the same attribute value
  21.  
  22. y = SimpleClass
  23. print "Reading the attributes from the objects in the list"
  24. for count in range(0,4):
  25. y = simpleList[count]
  26. print y.attr1
  27.  
  28. # So how do I (append, extend, copy or whatever) the elements of simpleList so that each entry
  29. # contains a different instance of the object instead of all pointing to the same one?
  30.  
  31. for count in xrange(4):
  32. x = SimpleClass()
  33. x.attr = count
  34. simplelist.append(x)
  35.  
  36. simplelist = [SimpleClass(count) for count in xrange(4)]
  37.  
  38. instancelist = [ MyClass() for i in range(29)]
  39.  
  40. instancelist[5].attr1 = 'whamma'
  41.  
  42. x = SimpleClass
  43.  
  44. x = SimpleClass()
  45.  
  46. import copy
  47.  
  48. x = SimpleClass()
  49.  
  50. for count in range(0,4):
  51. y = copy.deepcopy(x)
  52. (...)
  53. y.attr1= '*Bob* '* count
Add Comment
Please, Sign In to add comment