0

Hi, Dear my friends,

I has been using python for a while. But I just realized that when you make a copy of python class, it is copying a link to the class. So when you make the change to the attritutes of objects, it will change other attributes in other copied objects. That is not what I want. I have 30+ attributes in the class. SO I do not want to copy attribute by attributes. I tried copy.deepcopy but not work. Is there any suggestions on this? Many thanks inadvance.


Best,

John

2
Contributors
2
Replies
3
Views
9 Years
Discussion Span
Last Post by jliu66
0

So when you make the change to the attritutes of objects, it will change other attributes in other copied objects.

This is what a copy is. I think you may want separate instances of the class.

class some_class:
   def __init__(self, msg):
      print msg
      self.var=0

if __name__== "__main__":
   class_list=[some_class("test "+str(x)) for x in range(0, 2)]
   print "two different classes...see"
   for j in range(0, 2):
      print "     id for", j, id(class_list[j])
   class_list[0].var=1
   class_list[1].var=2
   print "first var=%d but second var=%d" % (class_list[0].var, class_list[1].var)

For the time being, __always__ print the class id's during testing. It is possible to think you have 2 instances of the class when you instead have two pointers to the same class.

Edit: If this in not what you want, post again with more detail on what result you want to achieve.

0

Thanks so much for your quick reply. Yes. I need to have 1000+ instances of a class. Also the number of attributes in the class may change so I do not want to make the change in copying the class object as I am writing function to deal with the copy of class.

I am using elcipse so that what are copied in each of class objects in debug mode.

By the way how I can copy the instances of a class with many attributes? I tried both assignment and COPY.deepCopy. Both are failed.

Thanks a lot.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.