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

Discussion in 'Python' started by Jean-Paul Calderone, Aug 12, 2006.

  1. On Sat, 12 Aug 2006 18:36:32 +0200, Anton81 <4ward.com> 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?


    You are trying to implement a constructor (__new__) for the Obj class, but you have actually implemented the initializer (__init__). In order to be able to control the actual creation of the instance object, you cannot use the initializer, since its purpose is to set up various state on an already created instance. Instead, you may want to use a class method:

    class Obj:
    def fromPickleFile(cls, fileName):
    return pickle.load(file(fileName))
    fromPickleFile = classmethod(fromPickleFile)

    You can then use this like so:

    inst = Obj.fromPickleFile('obj.dat')

    Jean-Paul


    >
    >Anton
    >--
    >http://mail.python.org/mailman/listinfo/python-list
    >
     
    Jean-Paul Calderone, Aug 12, 2006
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ralf W. Grosse-Kunstleve
    Replies:
    16
    Views:
    612
    Lonnie Princehouse
    Jul 11, 2005
  2. Ralf W. Grosse-Kunstleve
    Replies:
    18
    Views:
    612
    Bengt Richter
    Jul 11, 2005
  3. Ralf W. Grosse-Kunstleve
    Replies:
    2
    Views:
    420
    Dan Sommers
    Jul 12, 2005
  4. falcon
    Replies:
    0
    Views:
    396
    falcon
    Jul 31, 2005
  5. Anton81
    Replies:
    2
    Views:
    563
    Simon Forman
    Aug 12, 2006
Loading...

Share This Page