[英]Python 3.x: How to save and load data from within a class
I would like a class that in its initialize checks if filename
exists. 我想要一个在其初始化中检查filename
存在的类。 If it does it should initialize itself with filename
, otherwise it should run init. 如果这样做,则应使用filename
初始化自身,否则应运行init。 At a later point I can then run a save
method, saving the entire object. 之后,我可以运行save
方法,保存整个对象。
A sketch of what I want: 我想要的草图:
class data(object):
def __init__(self, filename):
if does_not_exist(filename): # create new
[... expensive computations]
self.save(filename)
else: # load existing
with open(filename,'rb') as fp:
self = pickle.load(fp)
def save(self, filename):
with open(filename,'wb') as fp:
pickle.dump(self, fp)
When loading I know that I can do something like 加载时,我知道我可以做类似的事情
tmp = pickle.load(fp)
self.a = tmp.a
self.b = tmb.b
...
But I hope that there is a better way 但我希望有更好的方法
I assume this question has been asked before, but couldn't find it :/ 我认为这个问题以前曾被问过,但是找不到它:/
Assigning to self
within __init__
is meaningless, since you're not modifying the object that self
points to -- you're just binding the variable name self
in the function to a different object. 在__init__
为self
赋值是没有意义的,因为您没有修改self
指向的对象,而是将函数中的变量名称self
绑定到了另一个对象。
What you can do instead is use a staticmethod
or classmethod
to perform the optional loading from cache: 您可以做的是使用staticmethod
或classmethod
从缓存执行可选加载:
class Data(object):
@classmethod
def init_cached(cls, filename):
if not os.path.exists(filename): # create new
result = cls(filename)
result.save(filename)
return result
else:
with open(filename, 'rb') as fp:
return pickle.load(fp)
def __init__(self, filename):
pass # [... expensive computations]
Now, use Data.init_cached()
instead of Data()
to initialize your object. 现在,使用Data.init_cached()
而不是Data()
来初始化您的对象。
A more fancy approach would involve overriding Data.__new__()
to achieve the same thing, but where initialization with Data()
transparently checks if a cached version exists: 更花哨的方法将涉及重写Data.__new__()
来实现相同的目的,但是使用Data()
进行初始化将透明地检查是否存在缓存的版本:
class Data(object):
def __new__(cls, filename):
if not os.path.exists(filename): # create new
return super(Data, cls).__new__(cls, filename, _save=True)
else:
with open(filename, 'rb') as fp:
return pickle.load(fp)
def __init__(self, filename, _save=False):
# [... expensive computations]
if _save:
self.save(filename)
Further reading: Python's use of __new__
and __init__
? 进一步阅读: Python对__new__
和__init__
的使用?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.