我试图(如果可能的话)改进下面的数据信息类,或寻找其他解决办法:
class Store(object):
def __init__( self, contents=None):
self.contents = contents
class DataContext(object):
def __init__( self, datastore ) : # datastore is of type store
self.store = datastore
def __enter__( self ) :
self.temp_store = copy.copy( self.store.contents ) # Improve upon this!
def __exit__( self, type, value, traceback ) :
self.store.contents = self.temp_store
实例使用:
data = Store( [1,2,3] )
print "Before context: ", data.contents
with DataContext( data ):
data.contents.append( 4 ) # Tampering with the data
print "Within context: ", data.contents
print "Outside context: ", data.contents
产出:
Before context: [1, 2, 3]
Within context: [1, 2, 3, 4]
Outside context: [1, 2, 3]
copy
对于大型数据结构来说成本昂贵。 怎样( 或有没有)一种清洁的方法来只存储上下文中数据结构的变化,然后 undo em > 在 < code> exit 中保存数据的具体变化?