【问题标题】:Can't reassign an object's attribute to another existing object无法将对象的属性重新分配给另一个现有对象
【发布时间】:2020-05-12 11:15:56
【问题描述】:

因此,作为我编程研究的一部分,我正在制作一个不相交的集合数据结构。但是,一种方法需要获取两个节点,如果它们不是相同的节点,则加入节点。这应该通过将一个节点的父属性设置为另一个节点来完成。但是,在使用调试器单步执行该方法后,父值永远不会改变。部分代码供参考:

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_root.parent = v_root 行正在执行,但 u_root.parent 在该行之后仍然为 None 。 u_root.parent 是属性而不是属性(也许?)
  • 听起来您希望 += 操作就地修改 int 值,但 int 值是不可变的。确实xy 可以引用同一个int 对象,但x += 1 实际上是x = x.__iadd__(1),并且由于int.__iadd__ 甚至没有定义,它进一步简化为x = x.__add__(1),即只需创建一个 int 值并将其分配给x,让y 引用原始值。
  • @TonySuffolk66 因此,当我使用调试器单步执行时,在调用u_root.parent = v_root 之后,u_root.parent 仍被分配了一个值None。我知道 Python 属性是一个属性,其中 getter 和 setter 用于控制对值的访问,但根对象是裸骨 Node 类的实例,因此没有使用 getter/setter 的值(除非我误解了 Python 中的属性是什么)。还是说我应该使用 getter/setter 来修改这个值?
  • 你不需要使用getter/setter——我只是想知道你是否在使用它们,因为它们可能会阻止你设置一些值;是v_root 绝对不是None 吗?
  • @TonySuffolk66 v_root 的值肯定不是None

标签: python python-3.x oop


【解决方案1】:

所以当我为代码编写单元测试以帮助调试时,代码开始工作了。我在编写测试时确实更改了一些代码,但我不完全确定是什么让事情正常进行。但它正在起作用,除非这个问题再次出现,否则我很满意。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 2011-02-17
    • 2017-11-01
    • 1970-01-01
    • 2011-06-06
    • 2021-10-10
    • 2020-11-10
    相关资源
    最近更新 更多