2011-11-28 84 views
0

我是Python新手,使用一组对象(Node)并试图迭代对象集合并打印出变量'H'。不幸的是我不断收到错误:(“AttributeError:'NoneType'对象没有属性'H'”)。任何有关为什么会发生这种情况的洞察力将不胜感激。Python 2.7'NoneType'对象没有任何属性

这是我的类节点,存储在集合中。

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 

这里是输入第一个节点的集合。后来,更多的节点进入,但现在只需添加一个正在制造一个头痛

open_list = set() 
start_row, start_col = start_loc 
open_list.add(Node(start_row, start_col, 0)) 

这里是代码引发错误行:(“AttributeError的:‘NoneType’对象有没有属性‘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] 
+8

您在表达式'open_node.H'处得到此异常,因为在您的程序的某个位置'open_node'中的值为'None'。 – wberry

+3

您显示的代码没有任何错误。尝试创建一个小的test.py,它将重现问题 –

回答

3

错误“AttributeError的:‘NoneType’对象没有属性‘H’”是指,在open_list节点中的一个被分配的值,而不是正在初始化“无”。 open_list在显示的行和错误行之间是否有任何事情发生?

+0

这看起来就是这样。在“行间”中,我在节点上调用with_parent方法,而不是先初始化它。我猜这就是我得到一个NoneType对象的原因。它源于我滥用@classmathod作为init覆盖。简单的解决方法是将父项作为构造函数的一部分添加,并将None作为第一个Node的父项值传递。万分感谢! –

相关问题