How to copy class objects?

Christian Tanzer tanzer at swing.co.at
Fri Feb 9 05:19:26 EST 2001


matthias.oberlaender at daimlerchrysler.com wrote:

> Is there some easy way to copy a class object? 
> 
> Here is the background:
> 
> 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)>
> 
> # I want a new class Xnew differing from X in that its instances use a 
> different scratch directory.
> Xnew = copyclass(X)
> # Now set scratchdir to something else
> Xnew.scratchdir = '/home/me/tmp'

tanzer [lib] 6 $ python2.0 
Python 2.0 (#5, Jan 30 2001, 11:08:38) 
[GCC 2.7.2.1] on linux2
Type "copyright", "credits" or "license" for more information.
>>> class X:
...   scratchdir = "/tmp/"
... 
>>> import new
>>> Xnew = new.classobj ("Xnew",(X,),{"scratchdir" : '/home/me/tmp'})
>>> Xnew.scratchdir 
'/home/me/tmp'
>>> issubclass (Xnew, X)
1
>>> 

-- 
Christian Tanzer                                         tanzer at swing.co.at
Glasauergasse 32                                       Tel: +43 1 876 62 36
A-1130 Vienna, Austria                                 Fax: +43 1 877 66 92





More information about the Python-list mailing list