copying classes?

Alex Martelli aleaxit at yahoo.com
Fri Dec 31 06:48:24 EST 2004


harold fellermann <harold.fellermann at upf.edu> wrote:
   ...
> > I always think that a well designed object should have a copyme method.
> > :=)

That would be __copy__ or __deepcopy__, but the __getstate__ /
__setstate__ approach is often preferable.

> take a look at the __setstate__ and __getstate__ documentation of copy
> (e.g. pickle) -- with them you can customize the copying task. Anyway,
> they work only on instance but not on class objects :(

They should, if you put them in the class of the class -- the metaclass.

>>> class mec(type):
...   def __copy__(cls):
...     return mec('copyof'+cls.__name__, cls.__bases__,
dict(vars(cls)))
... 
>>> class foo:
...   __metaclass__ = mec
... 
>>> bar = copy.copy(foo)
>>> bar.__name__
'copyoffoo'
>>> 


Alex



More information about the Python-list mailing list