I have a class where one of the methods is to replace the entire data encapsulate in the object when needed. However, I am not sure how to write the update the data to the object. Is it possible to assign the instance to the new instance, maybe something like self=new_self? I am aware I can create a new instance and then change the ptr to point to it, but would like to check if I can just update the same instance instead.
class Dictionary:
def __init__(self, collection_size):
self.dictionary = [Term() for _ in range(collection_size)]
self.collection_size = collection_size
def load(self, src):
with open(src, 'rb') as handle:
self = pickle.load(handle) # this is the part that needs editing
CodePudding user response:
I think a class method probably makes the most sense, something like
class Dictionary:
def __init__(self, collection_size):
self.dictionary = [Term() for _ in range(collection_size)]
self.collection_size = collection_size
@classmethod
def load_from_pickle(cls, src):
with open(src, 'rb') as handle:
cls = pickle.load(handle)
return cls
loaded_dictionary = Dictionary.load_from_pickle('path/to/pickle')
You probably want some "guardrails" on the load method to make sure you're unpickling an object that works.
At some point, you may also want some kind of Dictionary.merge, but that seems independent of initializing from a pickled object.
CodePudding user response:
Thanks for all the responses. I am using a mix of Andrew and Juanpa's answers. Because of the way my data is processed, it is unnecessary to do a merge but that adding try/except to load_from_pickle is a very good point. This is what I have settled on. Caveat: unsure if it is taboo to call init again.
class Dictionary:
def __init__(self, collection_size=None, dictionary=None):
self.dictionary = dictionary if dictionary else {}
self.collection_size = collection_size
self.collection_postings_list_ptr = 0
def load(self, src):
with open(src, 'rb') as handle:
new_dictionary = pickle.load(handle)
self.__init__(new_dictionary.collection_size, new_dictionary.dictionary)