如何交换 2 个物体' python 中的身份?
我有同一个类 RBnode
的 2 个实例 x
和 y
。 有没有办法交换它们的身份,以便所有对 x
的引用都转到 y
,反之亦然?
例如,
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 的所有相应属性。 但这需要很多行,因为节点的结构相当复杂。
I have 2 instances x
and y
of a same class RBnode
.
Is there a way to exchange their identities so that all reference to x
goes to y
and vice versa?
For example,
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
Actually I'm building an extension of Red-Black tree. Nodes of the tree are implemented as object. When writing the node removal method, I need to exchange two nodes, so that the node to be removed gets "at the bottom" of the tree.
First I tried to just exchange data in the two nodes:
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
But later an error occurred when remove_node
was called and the caller function was holding a reference to a node x
, which happens to be y.next
. Something like
x = y.next
self.remove_node(y)
x.parent
>>> AttributeError: 'NoneType' object has no attribute 'parent'
I could exchange all corresponding attributes of x
and y
.
But that takes pretty many lines since the structure of a node is rather complicated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我一定错过了一些东西,因为这有什么问题吗?
或者您是否打算重新分配所有名称,就像某种对象的身份盗窃?虽然可以在 C 级别上工作,但如果您可以在 python 中完成它而不会对事情造成重大破坏,我会感到非常惊讶。
I must be missing something, because what's wrong with this?
Or have you meant for reassigning all the names, like some kind of identity theft of an object? While it would be possible working at the C level, I would be pretty surprised if you could do it from within python without breaking things majorly.
“身份盗窃”在 Python 中是不可能的;但是,您通常可以交换两个不同对象的内容(甚至可能交换用户定义的类的类型):
"Identity theft" isn't possible in Python; however, you can usually exchange the contents of two different objects (and perhaps even exchange the type for user defined classes):