Re: Semi-newbie, rolling my own __deepcopy__



Michael Spencer wrote:
BTW, as I mentioned in a previous comment, I believe this would be more plainly written as type(self).__new__(), to emphasize that you are constructing the object without initializing it. (There is a explanation of __new__'s behaviour at http://www.python.org/2.2/descrintro.html#__new__).

There is also now documentation in the standard location:

http://docs.python.org/ref/customization.html

And just to clarify Michael's point here, writing this as __new__ means that __init__ is not called twice:

py> class C(object):
....     def __new__(cls):
....         print '__new__'
....         return super(C, cls).__new__(cls)
....     def __init__(self):
....         print '__init__'
....
py> c = C()
__new__
__init__
py> c2 = type(c)(); c2.__init__()
__new__
__init__
__init__
py> c3 = type(c).__new__(C); c3.__init__()
__new__
__init__

But definitely check the docs for more information on __new__. Some of the interworkings are kind of subtle.

STeVe
.



Relevant Pages

  • Re: Unit Testing and Instance Vars
    ... def do_clean_addresses ... you've probably spotted the subtle API change I've implemented ... initializing the instance variables too. ...
    (comp.lang.ruby)
  • Re: More baby squeaking - iterators in a class
    ... Thank you for the explanation. ... That is much clearer now, ... a bit with generators but have never tried to create a custom iterator. ... def __init__: ...
    (comp.lang.python)
  • Re: Why doesnt join() call str() on its arguments?
    ... > What I can't find an explanation for is why str.joindoesn't ... > automatically call str() on its arguments ... def __radd__: ... TypeError: sequence item 1: expected string, ...
    (comp.lang.python)
  • Re: trouble understanding inheritance...
    ... raise NotImplementedError ... def hasDefaultImplementation: ... print 'Initializing B' ... print "Boo Hoo!" ...
    (comp.lang.python)
  • Re: Some language proposals.
    ... Jacek Generowicz wrote: ... > Could somebody point me to an explanation of why closures are broken ... def b: ...
    (comp.lang.python)

Loading