use class in class

Robert Voigtländer r.voigtlaender at gmail.com
Tue Jan 21 05:20:48 EST 2014


Hi,

I have a problem using a class object within another class.
It is about the line:

self.openlist.append(Node(self.start, None, 0, 0))

If I use it in __init__ it works. If I use it in calcRoute(self) I get the following error:  local variable 'node' referenced before assignment The error occures in AMap.calcRoute()

Where is my mistake?


Thanks
Robert

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.cm as cm

class Node(object):
    def __init__(self, pos, parent, g , h):
        self.pos = pos
        self.parent = parent
        self.g = g
        self.h = h
        self.f = g+h

class NewAMap(object):
    def __init__(self, size, start, target):
        self.size = size
        self.start = start
        self.target = target
        self.openlist = []
        self.closedlist = set()
        self.EmptyValue = 0

        self.clear()
        self.addStart(self.start)
        self.addTarget(self.target)

        #self.openlist.append(Node(self.start, None, 0, 0))

    def clear(self):
        self.OccMap = np.zeros(shape=(self.size[0],self.size[1]),dtype=int)
    def display(self):
        print np.swapaxes(self.OccMap,0,1)

        self.PicMap = np.zeros(shape=(self.size[0],self.size[1]),dtype=(float,3))
        for x in xrange(0,self.size[0]):
            for y in xrange(0,self.size[1]):
                if self.OccMap[x][y] == 0:
                    self.PicMap[y][x]=(1,1,1)
                elif self.OccMap[x][y] == -1:
                    self.PicMap[y][x]=(0,0,0)
                elif self.OccMap[x][y] == -2:
                    self.PicMap[y][x]=(1,0,0)
                elif self.OccMap[x][y] == -3:
                    self.PicMap[y][x]=(0,0,1)
        #print self.PicMap
        plt.imshow(self.PicMap, interpolation='nearest')
        plt.show()

    def addBlocked(self, blockposs):
        self.OccMap[blockposs[0]][blockposs[1]]=-1
    def addStart(self, start):
        self.OccMap[start[0]][start[1]]=-2
    def addTarget(self, target):
        self.OccMap[target[0]][target[1]]=-3
    def calcRoute(self):
        self.openlist.append(Node(self.start, None, 0, 0))
        for Node in self.openlist: print Node.pos, Node.parent, Node.g, Node.h, Node.f


def main():
    AMap = NewAMap((20,20),(1,12),(12,12))
    for y in range(8,17): AMap.addBlocked((8,y))
    AMap.calcRoute()
    AMap.display()

if __name__ == '__main__':
    main()



More information about the Python-list mailing list