How to initialize an instance using pickle ()?

I want to define a class that can fill itself with reading from the serialized data of another instance. Here's the simplified code:

class MyClass(list): def __init__(self,**kwargs): if kwargs.has_key('fdata'): f = open(kwargs['fdata'],'r') self = pickle.load(f) print len(self) #prints 320 f.close() ... a = MyClass(fdata='data.dat') print len(a) #prints 0 

This is the result I get:

 320 0 

The problem is that the returned instance is always empty, although I can read all the elements inside __init__() What could be the reason for this?

+6
source share
2 answers

Assigning self inside a method simply reassigns the local name self to another object. Assigning hologram names in Python can never change any object - they simply rewrite the names.

Why don't you use straightforward

 with open("data.dat") as f: a = pickle.load(f) 

instead of creating a new class? If you don't like this, wrap it in a function, but it's not so useful to put this code in __init__() .

There are other ways to achieve the same effect. Probably the best way to achieve exactly what you are trying to do is to overwrite __new__() instead of __init__() - __new__() is called before a new instance is created, so you can simply return an unallocated instance instead of having to change the already built one.

+4
source

self is a regular local variable in Python. You cannot use self = other to make the object "become" something else, you just reassign the local one. You will have to restore the attributes one by one or use something like:

 self.__dict__ = pickle.load(f).__dict__ 

(I have not tested this last line, this can lead to an explosion of your kittens.)

+3
source

Source: https://habr.com/ru/post/919232/


All Articles