С помощью 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
thing.updateyourself() # pretty fast
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
Заставить объект сериализовать себя ⇐ Python
Программы на Python
1731123611
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
thing.updateyourself() # pretty fast
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
Подробнее здесь: [url]https://stackoverflow.com/questions/79171950/have-an-object-serialize-itself[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия