链表节点next_node赋值报错问题求助
链表节点next_node赋值报错问题求助
嘿,我帮你分析下你遇到的链表节点赋值报错问题哈~
首先先把你遇到的错误信息贴出来:
Cannot assign member "next_node" for type "node"
Expression of type "node | None" cannot be assigned to member "next_node" of class "node"
Type "node | None" cannot be assigned to type "None"
Type cannot be assigned to type "None"
再看看你写的代码(我先帮你把缩进整理了下):
class node : data = None next_node = None def __init__(self , data) : self.data = data def __repr__(self) : return "<node data: %s>" % self.data class linked_list : def __init__(self ): self.head = None def add (self , data): new_node = node(data) new_node.next_node = self.head self.head = new_node def __repr__ (self): nodes =[] current = self.head while current : if current is self.head: nodes.append ("[:head %s ]" % current.data) elif current.next.node is None : nodes.append ("[tail: %s ]" % current.data) else : nodes.append ("[:%s ]" % current.data) current = current.next_node return "->".join(nodes)
问题原因分析
- 类型推断冲突:你在
node类里把next_node初始化为None,但没有明确标注它的类型。如果用了类型检查工具(比如mypy),它会默认把next_node的类型推断成None,而你在add方法里把self.head(类型是node | None,因为链表初始化时head是None)赋值给new_node.next_node,这就导致了类型不匹配的报错——你试图把一个可能是节点或者None的值,塞给被推断成只能是None的属性。 - 拼写错误:在
linked_list的__repr__方法里,你写了current.next.node,这明显是笔误,应该是current.next_node,这个错误会导致代码运行时直接抛出AttributeError。
修复后的完整代码
# 类名改成大驼峰,符合PEP8编码规范 class Node: def __init__(self, data): self.data = data # 明确标注next_node的类型:可以是Node对象或者None self.next_node: Node | None = None def __repr__(self): return "<Node data: %s>" % self.data class LinkedList: def __init__(self): # 同样标注head的类型 self.head: Node | None = None def add(self, data): new_node = Node(data) new_node.next_node = self.head self.head = new_node def __repr__(self): nodes = [] current = self.head while current: if current is self.head: # 用f-string让字符串拼接更简洁 nodes.append(f"[:head {current.data} ]") # 修正拼写错误:next.node -> next_node elif current.next_node is None: nodes.append(f"[tail: {current.data} ]") else: nodes.append(f"[:{current.data} ]") current = current.next_node return "->".join(nodes)
修复点说明
- 类型标注:给
next_node和head明确标注类型为Node | None(Python 3.10及以上支持这种写法,如果你用的是更低版本,需要先from typing import Union,然后写成Union[Node, None]),这样类型检查工具就知道这些属性可以是节点或者None,不会再报错。 - 修正拼写错误:把
current.next.node改成current.next_node,解决运行时的属性错误。 - 编码规范优化:把类名改成大驼峰(
Node、LinkedList),符合Python的PEP8规范,代码可读性更强。
如果没有用类型检查工具,其实原来的代码除了拼写错误外,运行时不会有类型报错,但加上类型标注能让代码逻辑更清晰,也能提前发现潜在问题哦~
备注:内容来源于stack exchange,提问作者dawood 0
相关产品推荐
相关产品推荐

