Python 2.7 'NoneType'对象没有属性
我刚开始学习Python,正在处理一组对象(叫做Node),我想遍历这些对象并打印出变量'H'。可是我总是遇到一个错误:("AttributeError: 'NoneType' object has no attribute 'H'")。如果能帮我分析一下为什么会这样,我会非常感激。
这是我存储在集合中的Node类。
class Node:
def __init__(self, row, col, heuristic):
self.row = row
self.col = col
self.H = heuristic
self.parent = None
@classmethod
def with_parent(self, row, col, heuristic, parent):
self.row = row
self.col = col
self.H = heuristic
self.parent = parent
这是集合,里面先放了第一个Node。之后会添加更多的节点,但现在只添加一个就让我很头疼。
open_list = set()
start_row, start_col = start_loc
open_list.add(Node(start_row, start_col, 0))
这是抛出错误的那行代码:("AttributeError: 'NoneType' object has no attribute 'H'")
for open_node in open_list:
sys.stdout.write("H: " + str(open_node.H))
一旦我解决了这个问题,我真正的目标是根据启发式算法进行排序。
current = sorted(open_list, key=lambda open: open.H)[0]
1 个回答
3
这个错误“AttributeError: 'NoneType' object has no attribute 'H'”的意思是,open_list
中的某个节点被赋值为'None',也就是没有被正确初始化。你展示的代码行之间,open_list
有没有发生什么变化呢?