标签:pyc self har nbsp pre users create nat 应用
1.应用场景
(1)能保存对象的状态,并能够恢复到之前的状态
2.代码实现
#!/usr/bin/env python #! _*_ coding:UTF-8 _*_ class Originator(object): ‘‘‘这时基本类‘‘‘ def __init__(self, state): self.state = state def createMemento(self): ‘‘‘创建备忘录‘‘‘ return Memento(self.state) def setMemento(self, memento): ‘‘‘从备忘录中恢复‘‘‘ self.state = memento.state class Memento(object): ‘‘‘这时备忘录类‘‘‘ def __init__(self, state): self.state = state class Caretaker(object): ‘‘‘这时备忘录管理类‘‘‘ def __init__(self): pass def setMemento(self, memento): ‘‘‘将备忘录作为引用‘‘‘ self.memento = memento def getMemento(self): ‘‘‘从管理中获取引用‘‘‘ return self.memento if __name__ == "__main__": originator = Originator("state1") print originator.state memento = originator.createMemento() caretaker = Caretaker() caretaker.setMemento(memento) originator.state = "state2" print originator.state originator.setMemento(caretaker.getMemento()) print originator.state
结果:
/Users/liudaoqiang/PycharmProjects/numpy/venv/bin/python /Users/liudaoqiang/Project/python_project/day22_memento/memento_test.py
state1
state2
state1
Process finished with exit code 0
标签:pyc self har nbsp pre users create nat 应用
原文地址:https://www.cnblogs.com/liuzhiqaingxyz/p/9464101.html