【问题标题】:If class instances are always passed by reference?如果类实例总是通过引用传递?
【发布时间】:2019-09-20 18:52:09
【问题描述】:

我正在 Python3 中实现一个单独的 LinkedList。程序将“current_node”分配给“previous_node”,然后将“current_node”更改为“current_node.next”。我希望此更改也适用于“previous_node”,但事实并非如此。

class ListNode(object):
    def __init__(self, val):
        self.val = val
        self.next = None

a = [7, 8, 11, 3]

fst_node, sec_node, thd_node, frt_node = ListNode(a[0]), ListNode(a[1]), ListNode(a[2]), ListNode(a[3])

fst_node.next = sec_node
sec_node.next = thd_node
thd_node.next = frt_node

current_node  = sec_node
previous_node = current_node
print(previous_node, current_node)
current_node  = current_node.next
print(previous_node, current_node)

【问题讨论】:

  • 在进行最终分配之前,current_nodeprevious_node 都指向同一个对象。然后你让current_node 引用另一个对象。前一个节点不受影响。
  • FWIW,你可以做fst_node, sec_node, thd_node, frt_node = map(ListNode, a)

标签: python-3.x pass-by-reference singly-linked-list


【解决方案1】:

引用(变量)和对象本身不是一回事。

您可以更改变量以指向另一个对象,但不会更改该对象。

objRef = someObject
anotherObjRef = objRef
objRef = anotherObject
# anotherObjRef will still point to someObject!

但是,如果您修改对象中的某些内容(通过引用),则该对象将被修改,因此您将在所有引用中看到新值:

objRef = someObject
anotherObjRef = objRef
objRef.someData = something
# anotherObjRef.someData is something!

【讨论】:

    【解决方案2】:
    current_node  = sec_node
    previous_node = current_node  # current_node points to the same object as previous_node
    print(previous_node, current_node)
    current_node  = current_node.next  # changes where current_node points to
    print(previous_node, current_node)
    

    您是否注意到这里没有重新分配previous_node?只有current_node 是。这仍然是传递引用,您只是更改了 current_node 引用的内容,而单独留下 precious_node

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-13
      • 2013-03-20
      • 2011-07-13
      • 1970-01-01
      • 2019-08-22
      • 2022-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多