self=pickle.load(file)? (Object loads itself)

A

Anton81

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
 
G

Gary Herron

Anton81 said:
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:

.... pass
........ pass
....<class __main__.B at 0xb7da129c>

Both the __dict__ and the __class__.__name__ could be pickled.

Gary Herron
 
S

Simon Forman

Anton81 said:
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

Why are you trying to do this? Usually you would just say obj =
pickle.load(f) and be done with it (you could manipulate obj after it's
created, of course.) Why do you want to do obj = Obj() but have the
obj come from "obj.dat"?

Just curious.

Peace,
~Simon
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,743
Messages
2,569,478
Members
44,898
Latest member
BlairH7607

Latest Threads

Top