我正在尝试改进(如果可能的话)下面的 DataContext 类或找到替代解决方案:
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
对于大型数据结构来说,这可能很昂贵。什么是(或是否有)一种干净的方法来仅将更改存储在上下文中的数据结构中,然后在 期间撤消对数据的这些特定更改exit
?