On Friday June 18 2010 12:22:26 Payal wrote:
> Hi,
> I want to carry my classes around, so I wrote foo.py as,
> 
> #!/usr/bin/python
> 
> import pickle, shelve
> 
> f = shelve.open('movies')
> 
> class F(object) :
>     def __init__(self, amt) : self.amt = amt
>     def dis(self) : print 'Amount : ', self.amt
>     def add(self, na) :
>         self.amt += na
>         F.dis(self)
> 
> f['k'] = F
> x=F(99)
> f['k2']=x
> 
> Now in python interpreter I get,
> 
> >>> import shelve
> >>> f = shelve.open('movies')
> >>> F2=f['k']
> 
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
>   File "/usr/lib/python2.6/shelve.py", line 122, in __getitem__
>     value = Unpickler(f).load()
> AttributeError: 'module' object has no attribute 'F'
> 
> How do I carry around my classes and instances?

Classes don't really get pickled. Only a little bit of information describing 
the class. The class definition has to be visible to the interpreter when a 
class or one of its instances is unpickled.

Therefore you have to import the class first (IMHO, I didn't test anything):

from foo import F

import shelve
f = shelve.open('movies')
F2=f['k']

See:
http://docs.python.org/library/pickle.html#what-can-be-pickled-and-unpickled

"..., classes are pickled by named reference, so the same restrictions in the 
unpickling environment apply. Note that none of the class’s code or data is 
pickled, ..."


Eike.
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to