我有兩個實例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