![]() |
Pickle a Class
Does anybody have a good example of using a pickle dump and load on a class?
|
I used it to store the patterns tree for the TicTacToe game:
:
def makeSet ()::
...:
class Pattern: |
Interesting! You pickle dumped and loaded a list of class instances.
|
Can you pickle a class directly rather than its instance?
|
Haven't tried it; should take you a couple minutes to find out. Why would you want to pickle a class definition?
|
Quote:
|
I thought that if you pickle the instance of a class and load it into another program you have to supply the class.
Somewhere I found this note: "use class methods __getstate__ and __setstate__ to pickle a class" Pickle allows one to pickle any object, right? |
I'm still not saying you can't do it (I haven't checked), but you have to ask yourself if a class definition is an object. A blueprint is not a house or a lawnmower.
|
Well, in Python a class definition is an object. But class objects tend to have complications associated with them. Pickling a normal object instance is just a matter of looking at its __dict__ and then turning all its variables into strings. Pickling a class would involve including Python bytecode as well, which is somewhat harder.
Setting __getstate__ and __setstate__ on an object overrides Pickle's default serialization and deserialization routines, allowing you to define manually how your object is turned into a string. Other than that, you could play around with the code and code.compile modules, but they tend to be rather sparse on documentation. Is there a reason you really need to pickle a class? Could it not conceivably be done another way? |
Thanks Arevos, I think the easier way would be to import the class as a module.
|
| All times are GMT -5. The time now is 8:14 PM. |
Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC