Python Can';t重新分配对象';将属性添加到另一个现有对象
因此,作为我编程研究的一部分,我正在制作一个不相交的集合数据结构。但是,有一种方法需要获取两个节点,如果它们不是相同的节点,则连接节点。这应该通过将一个节点的父属性设置为另一个节点来完成。但是,在使用调试器单步执行该方法之后,父值永远不会更改。以下部分代码仅供参考:Python Can';t重新分配对象';将属性添加到另一个现有对象,python,python-3.x,oop,Python,Python 3.x,Oop,因此,作为我编程研究的一部分,我正在制作一个不相交的集合数据结构。但是,有一种方法需要获取两个节点,如果它们不是相同的节点,则连接节点。这应该通过将一个节点的父属性设置为另一个节点来完成。但是,在使用调试器单步执行该方法之后,父值永远不会更改。以下部分代码仅供参考: class Node: # a bare bones node class representing an entry in the disjoint set # track the ids as a static
class Node:
# a bare bones node class representing an entry in the disjoint set
# track the ids as a static variable
id = 0
def __init__(self):
self.id = Node.id
Node.id += 1
self.parent = None
self.rank = 0
问题代码本身,不相交集合类中的一个方法:
def union(self, u, v):
# the union operation is used to join two components into one
# this implementation uses the component's ranks to optimize the union operation
# in this varient, the component with the lesser rank is attached to the root with the greater rank
# the find method searches for a particular node, and returns a Node object
# (an instance of the above class)
u_root = self.find(u)
v_root = self.find(v)
# if u and v's root are the same, they are in the same component
# therefore, end the operation because they are already merged
if u_root.id == v_root.id:
return
# to simplify coding, we force the u root to always be the root of lower rank
if u_root.rank > v_root.rank:
u_root, v_root = v_root, u_root
# merge u root into v root
u_root.parent = v_root
# the offending bit of code that isn't working as intended
# if the two roots share the same rank, you can't just add one onto the other
if v_root.rank == u_root.rank:
v_root.rank += 1
我怀疑我是在假设变量赋值在Python中是如何工作的,尤其是在涉及Python对象时。我认为分配给Python对象的变量和属性将其视为引用,任何引用同一对象的变量都可以对其进行编辑。但是,我确实陷入了僵局,需要一些指导。因此,当我为代码编写单元测试以帮助调试时,代码开始工作。在编写测试时,我确实更改了一些代码,但我不完全确定是什么让事情起作用。但是它正在工作,除非这个问题再次出现,否则我很满意。当您在调试器中单步执行时-您是说行
u\u root.parent=v\u root
正在执行,但是u\u root.parent在该行之后仍然没有。u\u root.parent
是一个属性,而不是一个属性(可能?)。听起来您希望通过+=
操作修改int
值,但是int
值是不可变的。确实,x
和y
可以引用同一个int
对象,但是x+=1
实际上是x=x.\uuuuu-iadd\uuuuuuu(1)
,而且由于int.\uuuuu-iadd\uuuuuuuu
甚至没有定义,它进一步简化为x=x.\uuu-add\uuuuuuuuuuu(1)
,只需创建一个新的int
值并将其分配给x
,留下y
来引用原始值。@TonySuffolk66所以当我逐步使用调试器时,在调用u_root.parent=v_root
后,u_root.parent
仍然被分配一个值None
。我知道Python属性是一个使用getter和setter来控制对值的访问的属性,但根对象是裸体节点类的实例,因此没有使用getter/setter的值(除非我误解了Python中的属性)。或者你是说我应该使用getter/setter来修改这个值?你不需要使用getter/setter-我只是想知道你是否在使用它们,因为它们可能会阻止你设置一些值;v_root
绝对不是None
?@TonySuffolk66v_root
的值绝对不是None