Copy constructors

Guido van Rossum guido at python.org
Fri Aug 10 23:32:04 EDT 2001


"Alex Martelli" <aleaxit at yahoo.com> writes:

> "Joal Heagney" <s713221 at student.gu.edu.au> wrote in message
> news:3B73B115.9981318D at student.gu.edu.au...
>     ...
> > I LOVE this language. Alex, you're empty class trick just made it into
> > my private python scrap-book.
> 
> Glad you liked it!  That convinced me to post it as a recipe to the
> cookbook, with slightly more complete discussion -- please see
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66507
> Comments, ratings and feedback are welcome, as usual!

While I probably introduced this myself (pickle uses it), I have one
reservation.  Assignment to self.__class__ is unique to Python -- it's
not an idiom one can easily translate to other languages.  It's also a
relatively new Python feature (I don't even know if Jython supports
it).

But maybe more importantly, I don't know how to support this esoteric
feature after the type/class unification is complete.  Under the new
system, not all instances are born the same: instances may have slots
for instance variables rather than a __dict__ -- using slots makes for
more space-efficient instances.  (Having a __dict__ is still the
default, and an instance can have both slots and a __dict__.)

Fortunately, the type/class unification has a different idiom
available to avoid __init_: __new__.  There are two parts to object
construction, __new__ and __init__.  __new__ is a class method, and
constructs a minimal object.  After __new__ has returned an
instance,__init__ is called to further initialize the instance.  At
least that's what the normal constructor (calling the class) does.
You can call __new__ directly to construct an instance bypassing
__init__.

--Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-list mailing list