像为类定义复制协议这样简单的事情呢?在import copy
class Graph(object):
def __init__(self):
self.data = [1,2,3]
self.manager = None
def __getstate__(self):
return {
'data': self.data,
'manager': self.manager
}
def __setstate__(self, state):
self.manager = state.pop('manager')
for name, val in state.iteritems():
setattr(self, name, copy.copy(val))
class Manager(object):
def __init__(self):
self.data = [4,5,6]
self.graphs = []
def __getstate__(self):
return {
'data': self.data,
'graphs': self.graphs
}
def __setstate__(self, state):
self.graphs = [copy.copy(g) for g in state.pop('graphs')]
for name, val in state.iteritems():
setattr(self, name, copy.copy(val))
您只需将管理器定义为引用,其他所有内容都将按您希望的方式复制。在
示例:
^{pr2}$