By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,713 Members | 764 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,713 IT Pros & Developers. It's quick & easy.

__new__ to create copy

P: n/a
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
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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" <me*****@hadiko.de> schrieb im Newsbeitrag
news:bv**********@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

Jul 18 '05 #2

P: n/a
> 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
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.