我有两个实例x
和y
同一类RBnode
。 有没有办法交换他们的身份,以便所有参考x
去y
,反之亦然?如何在Python中交换2个对象的身份?
例如,
x = RBnode()
y = RBnode()
x.data = 1
y.data = 2
L = [x,y]
exchange_identity(x,y)
print x.data, y.data, (L[0] is y)
>>> 2 1 True
其实我建立红黑树的延伸。树的节点被实现为对象。在编写节点删除方法时,我需要交换两个节点,以便要删除的节点位于树的“底部”。
首先,我想只是在两个节点交换数据:
def remove_node(self, y):
''' remove node y from tree
return (y.key,y.value) if successful'''
... ... ...
# exchange y's data with that of its successor y.next
y.key = y.next.key
y.value = y.next.value
但后来发生错误时remove_node
被调用,调用函数拿着一个参考节点x
,这恰好是y.next
。喜欢的东西
x = y.next
self.remove_node(y)
x.parent
>>> AttributeError: 'NoneType' object has no attribute 'parent'
我可以交流的x
和y
所有相应的属性。 但是,由于节点的结构相当复杂,因此需要很多行。
您可能会感兴趣的http://stackoverflow.com/questions/ 7255777/can-i-efficient-swap-two-class-instances-by-swapping-dict(but there be dragons。) – DSM 2012-01-31 05:38:06