How to copy class objects?

Alex Martelli aleaxit at yahoo.com
Fri Feb 9 07:09:19 EST 2001


<matthias.oberlaender at daimlerchrysler.com> wrote in message
news:960b75$a2e$1 at news.sns-felb.debis.de...
> This is the question I'd like to be answered:
>
> Is there some easy way to copy a class object?

There are a few.  As usual, "the simplest way that will possibly work"
tends to be best.

> In order to generate classes from templates I'd prefer the following
method
> over writing additional wrapper function
>
> class X:
>   sratchdir = "/tmp/"
>   <blabla    (methods using scratchdir)>

Presumably, the methods use, specifically, self.scratchdir, right?

It's very different if they use X.scratchdir (which they shouldn't!).

If they just use an _unqualified_ scratchdir, they won't compile
(unless they accidentally hit a global one:-).


> # I want a new class Xnew differing from X in that its instances use a
> different scratch directory.
> Xnew = copyclass(X)

It's just:

class Xnew(X):
    pass

> # Now set scratchdir to something else
> Xnew.scratchdir = '/home/me/tmp'

Will work fine (as long as the methods use self.scratchdir as they
should).  Yep, Python gives you "virtual attributes" (if you play
your cards right:-)...!!!-)

Alternative approaches, with marginal advantages in strange cases,
include setting the __bases__ attribute of an empty class that is
otherwise generated, using new.classobject, mucking around with
dictionaries, etc, etc.  But the class statement is simplest, and
thus the solution most often advisable.


Alex






More information about the Python-list mailing list