save class

nik nikbaer at gmail.com
Wed Jun 13 22:11:22 EDT 2007


On Jun 13, 6:48 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Wed, 13 Jun 2007 22:20:16 -0300, nik <nikb... at gmail.com> escribió:
>
> > I would like to create a class and then save it for re-use later. I
> > have tried to usepickle, 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

Thanks for the response.

It would seem that I want to actually save the source code for the
class. I know that I could of course open up an editor and just make
it, but my ideal would be to have the base class, Map, be able to make
the sub-classes. I don't want the class definition. What I want is an
actual class that I could later import and use somewhere else. I am
planning to have each one of these map objects contain a different
dictionary and then be able to import the map into the application,
but have certain methods defined in the Map super-class to draw data
out of the specific map's specific dictionary. I hope that makes
sense.

Something like,
class Map:
     dict = {}
     def DoSomething(self):
         pass

     def MakeNewMapSubClass(self, newclassname):
         """ make a new file, newclassname.py that contains a new
class
             newclassname(Map) that inherits from base-class Map.

Thanks,
Nik




More information about the Python-list mailing list