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

Jean-Paul Calderone exarkun at divmod.com
Sat Aug 12 12:55:37 EDT 2006


On Sat, 12 Aug 2006 18:36:32 +0200, Anton81 <forum at anton.e4ward.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
>



More information about the Python-list mailing list