save class

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Jun 13 21:48:22 EDT 2007


En Wed, 13 Jun 2007 22:20:16 -0300, nik <nikbaer at gmail.com> escribió:

> I would like to create a class and then save it for re-use later. I
> have tried to use pickle, but am not sure if that is right. I am
> sorry, but I am new to python.

Do you want to save the *source*code* of your class, or do you want to  
save created *instances* -objects- of your classes to retrieve them later  
(like a database)?

> Basically, I have a class, Map. I want to be able to create new maps:
> MapA, MapB... that have Map as the base class.
>
> start with-
> class Map:
>     pass
>
> and then get a different class
>
> class MapA(Map):
>     pass
>
> that can be saved in a .py file for re-use

You just create the .py file with any text editor, containing the source  
code for all your classes.

> so far I thought that -
> cls = new.classobj('MapA', (Map, ), {})
> file = open('somefile', mode='w')
> pickle.dump(cls, file)
>
> -might work, but it didn't.... can anybody point me in the right
> direction? I know that classes must get saved from the interactive
> console, so I would think that it would be a standard thing to do.

This would try to save the *class* definition, which is usually not  
required because they reside on your source files.
If this is actually what you really want to do, try to explain us exactly  
why do you think so. Chances are that there is another solution for this.

-- 
Gabriel Genellina




More information about the Python-list mailing list