__new__ to create copy

U

Uwe Mayer

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):
....

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
 
F

F. GEIGER

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
 
J

Josiah Carlson

How is such a thing done correctly? Where is the exact difference between
__new__ and __init__?

For some reason, I'm not finding the doc page, but I am pretty sure the
below is the case.
If __new__ exists, it will be called.
If __new__ exists, it must call __init__ for __init__ to be called.
If __new__ doesn't exist, __init__ will be called, if it exists.


How I usually copy my classes:

class blah:
def __init__(self, arg1, arg2, ...):
self.arg1 = arg1
self.arg2 = arg2
...
def copy(self):
return blah(self.arg1, self.arg2, ...)

It may not be pretty, but it works.

- Josiah
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top