I want to define a class that is able to populate itself 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 output I obtain:
320
0
The problem I have is that the instance returned is always empty, even though I am able to read all the elements inside __init__() What can be causing this?
Assigning to
selfinside a method simply rebinds the local nameselfto a different object. Assignments to bare names in Python can never modify any object – they just rebind names.Why don’t you use the straight-forward
instead of constructing a new class? If you don’t like this, wrap this in a function, but it’s not that useful to put this code into
__init__().There are other ways to achieve the same effect. Probably the best way to achieve exactly what you are trying is to overwrite
__new__()instead of__init__()–__new__()is called before the new instance is constructed, so you can simply return the unpickled instance instead of having to modify an already constructed one.