Anton81 wrote: > Hi! > > it seems that > > class Obj: > def __init__(self): > f=file("obj.dat") > self=pickle.load(f) > ... > > doesn't work. Can an object load itself with pickle from a file somehow? > What's an easy solution? > > Anton > That won't work, but the following will. An object's attributes can be accessed and set through the __dict__ attribute, and its class through the __class__ attribute:
>>> class A: # define class A ... pass ... >>> a = A() # create an instance >>> a.__dict__ # It has no attributes {} >>> a.__dict__ = {'c':1, 'b':2} # Give it some >>> a.b # Verify 2 >>> a.c 1 >>> a.__class__ # Examine its class <class __main__.A at 0xb7da12fc> >>> class B: ... pass ... >>> a.__class__ = B # Change its class >>> a.__class__ # Verify <class __main__.B at 0xb7da129c> Both the __dict__ and the __class__.__name__ could be pickled. Gary Herron -- http://mail.python.org/mailman/listinfo/python-list