Method returning new instance of class?
Jp Calderone
exarkun at divmod.com
Sat Sep 4 13:33:52 EDT 2004
Arthur wrote:
> "Martin v. L=F6wis" <martin at v.loewis.de> wrote in message
> news:4139a87a$0$30204$9b622d9e at news.freenet.de...
> =
>>Arthur wrote:
>>
>>>Essentially I am trying to create a non-destructive tranformation of an
>>>instance of a class - is one way of putting it.
>>>
>>>The way I am currently conceptualizing a solution, what I need is a
> =
> method
> =
>>>of the class that returns a new instance of the class.
>>
>>So you want a copy of the object. I'd use copy.copy for this, perhaps
>>copy.deepcopy.
> =
> =
> That was my first instinct. And perhaps my problem is in here somewhere.
> =
> The app is graphical, and I use a Python extensions in C++ using the Boost
> library (vpython, new version). My class instance has an attribute which=
is
> a vpython object. Copy.copy doesn't get me where I need to be because my =
new
> instance gets a reference to the same vpython object, and changes to it a=
re
> reflected in the original instance. Copy.deepcopy doesn't work for more
> obscure reasons. I get an error message generating up from vpython when I
> try to change an attribute of the object on the new instance - though I =
am
> interacting with it in the same manner that works fine when performed on =
the
> original instance.
> =
> But do you see any reason why this might be?
> =
> If it sounds totally illogical, I'll go back and check myself - because of
> course the actual sitruation is a bit more complicated than what I am
> describing, and I guess it is possible I am falling off the ledge somewhe=
re
> else.
It sounds terribly logical. Copying objects is extremely difficult =
to do correctly. There is no way to do it generically and correctly. =
Make the copy too shallow, and you get unwanted shared state. Make the =
copy too deep and the new object is useless. How do you decide how deep =
is deep enough? You can't, at least not without intimate knowledge of =
the object you're dealing with.
Once you figure out exactly how deep you need to make your copy, you =
can tell copy.deepcopy() how to behave with the copy_reg module. Of =
course, since this knowledge is quite closely tied to VPython, it should =
really be *part* of the VPython package, so that changes to the =
internals of VPython can be made right alongside changes to the code =
which knows how to copy its objects.
Jp
More information about the Python-list
mailing list