On Sat, 12 Aug 2006 18:36:32 +0200, Anton81 <[EMAIL PROTECTED]> 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
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to