Python 多重赋值会引发错误,但单独赋值不会
Posted
技术标签:
【中文标题】Python 多重赋值会引发错误,但单独赋值不会【英文标题】:Python multiple assignment throws error but separate assignment does not 【发布时间】:2020-01-16 19:31:14 【问题描述】:我正在反转一个链表,但是多个赋值会破坏这个功能,而单独的赋值不会。有人可以解释这两个代码段之间的执行差异吗?
我知道表达式的右侧是在赋值之前进行评估的,但是据我所知,如果是这种情况,我将无处可访问 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
有人能解释一下这两个代码段的执行区别吗?
【问题讨论】:
如果您不打算使用它,分配给temp
有什么意义?最后一行是访问不正确的cur.next
,因为cur.next
已经被重新分配。 cur = temp
会在那里工作。
还会报错吗? (错误是什么?)
已编辑,意味着结尾有 cur = temp
在问题中添加了错误信息
【参考方案1】:
我也发现这种行为令人惊讶,但是一旦考虑到对象属性和执行顺序将如何在这样的实例中工作,它就很有意义。
为了自己演示,我做了一个MCVE 的例子:
class A:
def __init__(self, a):
self.a = a
a = A(1)
a, a.a = a.a, None
这些问题是虽然右侧是一次全部评估,但左侧仍然是从左到右评估。这意味着a
将完美地重新分配给a.a
,但是在评估左侧的a.a
时,a
将不再具有.a
属性,因为它已被重新分配给一个int。
将最后一行替换为以下内容具有相同的结果,并且可以更清楚地说明问题:
t = a.a, None
a = t[0]
a.a = t[1]
【讨论】:
谢谢,我没有考虑左边的分配顺序!以上是关于Python 多重赋值会引发错误,但单独赋值不会的主要内容,如果未能解决你的问题,请参考以下文章