Initialize object from the pickle in the __init__ function

Viewed 4289

I have a class where I would like to instantiate the object in several ways depending on the arguments. When I pass a filepath to the function __init__ it should restore all parameters from the object saved as a pickle file. Is there any smart way to do so, something like self=load(...)

3 Answers

This is probably not a "smart way" but if you prefer a third option (besides new and factory):

class myclass:

  def __init__(self, filename):

    with open(filename, 'rb') as f:
      myinstance = pickle.load(f)

    for k in myinstance.__dict__.keys():
      setattr(self, k, getattr(myinstance, k))

This loops through all properties of the loaded instance (myinstance) and sets the corresponding ones in the instance that is initialized (self).

Related