__new__ to create copy

F. GEIGER fgeiger at datec.at
Fri Feb 6 11:48:01 CET 2004


I do object copies this way:

import copy

a = A()
aa = copy.copy(a)

or

aa = copy.deepcopy(a)

You can wrap this up into a method of course, which then can decide whether
to do a deep copy or not.

HTH
Franz GEIGER


"Uwe Mayer" <merkosh at hadiko.de> schrieb im Newsbeitrag
news:bvvprg$81b$1 at news.rz.uni-karlsruhe.de...
> Hi,
>
> I want to create a copy of an object from out of its base class:
>
> class A(object):
>   def copy(self):
> ...
>
> class B(A):
> ...
>
> >>> b = B()
> >>> b.copy()
>
> I'm not sure how to do this:
>
> def copy(self):
>     cpy = self.__new__(self.__class__)
>     return cpy
>
> seems not to call the constructor __init__().
>
> How is such a thing done correctly? Where is the exact difference between
> __new__ and __init__?
>
>
> Thanks
> Uwe





More information about the Python-list mailing list