Reputation: 83
I have read over the answers on Saving an Object (Data persistence) but it isn't really what I was looking for. I don't want to save the class state in a file.
Here's what I'm trying to implement:
class A():
def some_function(self):
# save class state here - (*)
if something:
#make changes to class attributes
if something_again():
# revert back to class state at - (*)
How can I save the class state at a particular point?
Upvotes: 0
Views: 158
Reputation: 2247
You could implement something like this
class A():
def __init__(self):
self.prev_state = dict()
self.field_1 = 1
self.field_2 = 2
self.save_fields = (
"field_1",
"field_2"
)
self.save_state()
def save_state(self):
for f in self.save_fields:
self.prev_state[f] = getattr(self, f)
def restore_state(self):
for f in self.save_fields:
setattr(self, f, self.prev_state[f])
a = A()
a.field_1 += 1
print(a.field_1) # 2
a.restore_state()
print(a.field_1) # 1
Upvotes: 1