首页 > 解决方案 > Python 多重赋值会引发错误,但单独赋值不会

问题描述

我正在反转一个链表,但是多个分配会破坏这个功能,而单独的分配不会。有人可以解释这两个代码部分之间的执行差异吗?

我知道表达式的右侧是在赋值之前评估的,但是据我所知,如果是这种情况,我将无处访问 None.next。

class Node:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def clear():
    print("------------------------------------------")

def isPalindrome(A):
    if A is None:
        return True

    # get length
    cur, length = A, 1
    while cur.next is not None:
        cur = cur.next
        length += 1

    # go to second half
    cur, index = A, 0
    while index < (length + 1) / 2:
        cur = cur.next
        index += 1


    # start reversing
    prev = None
    while cur is not None:
        # this throws error? what is the difference?
        # cur, prev, cur.next = cur.next, cur, prev
        temp = cur.next
        cur.next = prev
        prev = cur
        cur = temp

    # now prev has reversed second half
    secondHalf = prev
    firstHalf = A

    # traverse both halves, comparing Ll[n] with Ll[length - 1 - n]
    while secondHalf is not None and firstHalf is not None:
        if firstHalf.val != secondHalf.val:
            return False

        firstHalf = firstHalf.next
        secondHalf = secondHalf.next

    return True

# even length simple case
def isPalindromeTest():
    A = Node(1, Node(1, Node(1, Node(1))))

    clear()
    print(isPalindrome(A))

isPalindromeTest()

我希望注释行

# cur, prev, cur.next = cur.next, cur, prev

相当于

temp = cur.next
cur.next = prev
prev = cur
cur = cur.next

如果我使用第一个代码部分,则会出现错误消息:

Traceback (most recent call last):
  File "linked_lists.py", line 1089, in <module>
    isPalindromeTest()
  File "linked_lists.py", line 1052, in isPalindromeTest
    print(isPalindrome(A))
  File "linked_lists.py", line 1027, in isPalindrome
    cur, prev, cur.next = cur.next, cur, prev
AttributeError: 'NoneType' object has no attribute 'next'

Implying that I am accessing None.next, which in this context it would have to be prev.next if anything?

第二段代码:

------------------------------------------
True

有人可以解释这两个代码部分之间的执行差异吗?

标签: pythonpython-3.xoperator-precedenceassignment-operatororder-of-execution

解决方案


我还发现这种行为令人惊讶,但是一旦考虑到对象属性和执行顺序将如何在这样的实例中工作,它就很有意义。

为了自己演示,我做了一个MCVE示例:

class A:
    def __init__(self, a):
        self.a = a

a = A(1)
a, a.a = a.a, None

这些问题是,虽然右侧是一次性评估的,但左侧仍然是从左到右评估的。这意味着aa.a完美地重新分配,但a.a在左侧被评估时,a将不再具有该.a属性,因为它已被重新分配给一个 int。

用以下内容替换最后一行具有相同的结果,并且可以更清楚地说明问题:

t = a.a, None
a = t[0]
a.a = t[1]

推荐阅读