
在 Python 中,尝试访问 None 对象的属性(如 nextNode.val)会抛出 AttributeError;而通过 is not None 显式判空或合理使用异常处理,可避免程序崩溃——这是链表遍历中最基础也最关键的防御性编程实践。
在 python 中,尝试访问 `none` 对象的属性(如 `nextnode.val`)会抛出 `attributeerror`;而通过 `is not none` 显式判空或合理使用异常处理,可避免程序崩溃——这是链表遍历中最基础也最关键的防御性编程实践。
在 LeetCode 经典题「两数相加」(Add Two Numbers)中,链表节点定义如下:
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
当你执行 nextNode = l1.next 后,nextNode 可能是 ListNode 实例,也可能是 None(尤其当 l1 是尾节点时)。此时直接调用 nextNode.val 会触发:
AttributeError: 'NoneType' object has no attribute 'val'
✅ 正确做法:始终在访问前校验非空
if nextNode is not None:
print(nextNode.val)
else:
print("Reached end of list")
⚠️ 错误示范:在 except 块中重复访问未判空的 nextNode.val
try:
print(nextNode.val)
except:
print(nextNode.val) # ❌ 再次触发 AttributeError!
该写法会导致二次崩溃:首次 nextNode.val 抛出异常 → 进入 except → 第二次 nextNode.val 仍为 None → 再次抛出异常,且无外层 try 捕获,程序终止。
✅ 安全的异常处理(仅作补充方案,不推荐替代显式判空):
try:
print(nextNode.val)
except AttributeError:
print("nextNode is None or missing 'val'")
但更推荐主动防御(explicit null check)而非被动捕获,原因包括:
- 性能更优(避免异常开销);
- 语义清晰,体现“此处可能为空”的设计意图;
- 符合 Python 的 EAFP(Easier to Ask for Forgiveness than Permission)原则的合理变体——实际应遵循 LBYL(Look Before You Leap) 在明确可预判的场景(如链表遍历)中优先判空。
? 总结:
-
None是 Python 的空对象,不具备任何实例属性; - 链表操作中,
node.next为None是正常终止信号,不是 bug; - 所有对
node.next.val、node.next.next等链式访问,都必须确保每级非空(逐级判空或用getattr(node, 'next', None)等工具辅助); - 在算法题调试中,建议打印
type(node)和node值辅助定位(如print(type(nextNode), nextNode)),避免依赖 IDE 或样例输出的“侥幸成功”。
Python免费学习笔记(深入):立即使用
在学习笔记中,你将探索 Python 的核心概念和高级技巧!











