由于AttributeError

问题描述

当我尝试调用属于Frontier类的print_frontier()时,会发生AttributeError: 'NoneType' object has no attribute 'print_puzzle',其中print_puzzle()是State类的成员函数,并在print_frontier()内部被调用。

print_frontier()通过使用self.nodes打印每个拼图来打印print_puzzle()中存储的所有拼图。

值得一提的是,当我在主程序中删除frontier.increase_limit()时,代码成功按预期打印了一个难题,我担心问题应该出在increase_limit()内部,但我不能找出问题所在。

class Frontier:

    ...


    def increase_limit(self) -> None:
        nodes_to_remove = []
        nodes_to_add = []
        current_nodes = self.nodes.copy()
        self.nodes.clear()

        for node in current_nodes:

            if node is None:
                raise Exception('"node" is a NoneObject')

            empty_tile_pos = node.get_empty_tile_pos()

            if empty_tile_pos not in [0,1,2]:
                nodes_to_add.append(
                    State(node.puzzle,node.path).move_tile('up'))
            if empty_tile_pos not in [6,7,8]:
                nodes_to_add.append(
                    State(node.puzzle,node.path).move_tile('down'))
            if empty_tile_pos not in [0,3,6]:
                nodes_to_add.append(
                    State(node.puzzle,node.path).move_tile('left'))
            if empty_tile_pos not in [2,5,node.path).move_tile('right'))

            nodes_to_remove.append(node)

        for node in current_nodes:
            if node not in nodes_to_remove:
                self.nodes.append(node)

        self.nodes.extend(nodes_to_add)
        self.depth += 1

    def print_frontier(self):
        for node in self.nodes:
            node.print_puzzle()  # calling a function of the State class

这里是“状态”类供参考:

class State:

    ...

    def print_puzzle(self):
        print()
        for tile in self.puzzle:
            if self.puzzle.index(tile) in [2,8]:
                print(tile,end='\n')
            else:
                print(tile,end=' ')
        print(self.path,end='\n')

这是我测试班级时的主要程序:

start_state = State([0,2,4,6,8,1])
frontier = Frontier(start_state)
frontier.increase_limit(). # works well without this line
frontier.print_frontier()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)