Заставить объект сериализовать себяPython

Программы на Python
Ответить
Anonymous
 Заставить объект сериализовать себя

Сообщение Anonymous »

С помощью JSON или Pickle я могу создать экземпляр объекта и сохранить его следующим образом:
import pickle
thing = Thingy(some_data) # takes a while...
# ... do stuff with thing then save it since it mostly is the same
with open(filename, 'wb') as f:
pickle.dump(thing, f)

И прочитайте его, если файл сериализации существует:
if thingy_file.exists():
with open(filename, 'rb') as f:
thing=pickle.load(f) # Thingy(some_data) restored
else:
thing=Thingy(some_data) # takes a while...

Однако эта сериализация выполняется вне создания экземпляра объекта Thingy...
Теперь предположим, что у меня есть некоторый пользовательский объект с внутренними данными, которые создание занимает много времени:
class Thingy:
def __init__(self, stuff...)
# this take a while the first time, but could be instant if read back
# pseudo'ish:
if self.file.exists():
print(f'Existing Thingy {self.file} found...')
# What I am trying to do here is read from a serialization file the
# data comprising the last time THIS INSTANCE of Thingy existed
with open(self.file, 'rb') as f:
self=pickle.load(f)
else:
# bummer this is gonna take a while...

# the rest of the object code...
# HERE we either have calculated a Thingy or have read it back into itself
# The instance may be modified -- now save its own self to be re-read in future:

def save_my_own_instance(self):
# now self is this instance of Thingy that will be serialized to disk
# magic I do not know...
with open(self.file, 'wb') as f:
pickle.dump(my_own_instance_data, f, pickle.HIGHEST_PROTOCOL)

Итак, вопрос: как объект использует сериализацию для восстановления своих собственных данных в свой собственный экземпляр? А как насчет сохранения себя внутри собственного экземпляра?

Некоторые особенности того, что такое Thingy:
from pathlib import Path

p=Path(a_HUGE_tree_of_data_files) # 750k plus large image files

tree_data=Thingy(p)
# initial run on p is hour+
# the tree changes very little, so an update of Thingy(p)
# only takes seconds

# I don't want to educate the user to check for a previous run
# It should be automatic


Подробнее здесь: https://stackoverflow.com/questions/791 ... ize-itself
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»