When I am instantiating a particular class I have written, I give it a name and several properties as arguments to __init__. Given the name passed, my __init__ tries to find a file on disk that applies to that name and instead of processing the other arguments passed it reads all those from the file. And if the file is not found, the arguments are used instead.
Now I wonder, if I wanted to use pickle to store the whole object instead of using my own routines for writing files, how would I accomplish the loading? I can’t unpickle my object inside __init__ because there the object has already been created, right?
One idea I have is to write a class method that I would use for instantiation instead which returns an unpickled object if it is stored on disk, otherwise it will make a new object with the passed parameters.
An other idea is to use __new__ instead of a class method that will return an object, however I don’t know if that is the intended use of __new__.
Are these ideas any good or is there a better way to accomplish this?
Use a factory function instead of doing this in
__init__. Example: