【发布时间】:2019-11-25 05:39:16
【问题描述】:
我正在编写一个新库,我想保留一些对象。我想使用 mixin 或某种适配器,所以我不必立即实现数据库。我现在正在使用 pickle 来存储对象。
假设我有一个 User 类。如果泡菜存在,我想从文件夹中加载用户。我写了一个 Persistor 类,它接受一个对象并将其写入指定的位置。我是否让 User 类继承自 Persistor 类?如果是这样,当用户类被实例化时,如果泡菜存在,我该如何用加载的对象替换该对象?还是我创建一个 UserPersistor 类?我只是想从 User 类中抽象出状态的加载和保存。
class User(Persistor???):
"""
Central class to hold all user attributes and relationships.
"""
def __init__(
self,
first_name: str,
username: str,
date_of_birth: datetime.date
):
self.first_name = first_name
self.username = username
self.date_of_birth = date_of_birth
import pickle
import os
class Persistor:
"""
Class whose job is to save and load state until we need a database.
"""
def __init__(
self,
persistence_key
):
self.persistence_key = persistence_key
self.persistence_path = "data/" + persistence_key
@property
def save_exists(self):
return os.path.exists(self.persistence_path)
def save(self):
outfile = open(self.persistence_path, 'wb')
pickle.dump(self, outfile)
outfile.close()
def load(self):
if self.save_exists:
infile = open(self.persistence_path, 'rb')
db = pickle.load(infile)
infile.close()
return db
def delete(self):
if self.save_exists:
os.remove(self.persistence_path)
【问题讨论】:
标签: python oop inheritance pickle mixins