mtaliaf
mtaliaf

Reputation: 81

Creating a new object from a function in python

class SlidePuzzle(object):

    def __init__(self, state = None):
        if state == None: state = [[1,2,3],[4,'N',5],[6,7,8]]
        self.puzzle_state = list(state)

    def isValidMove(self, move):
        x,y = self.getBlank()

        if move == 'up':
            return y != 0
        elif move == 'down':
            return y != 2
        elif move == 'left':
            return x != 0
        elif move == 'right':
            return x != 2
        else:
            print "Invalid Move"
            return 0
    def getValidMoves(self):
        validMoves = ['up', 'down', 'left', 'right']

        if not self.isValidMove('down'):
            validMoves.remove('down')
        if not self.isValidMove('up'):
            validMoves.remove('up')
        if not self.isValidMove('right'):
            validMoves.remove('right')
        if not self.isValidMove('left'):
            validMoves.remove('left')

        return validMoves

    def generateChildren(self):
        return [SlidePuzzle(self.puzzle_state).move(m) for m in self.getValidMoves()]

If I run these commands:

- p = SlidePuzzle()
- print p
- p.move('up')
- print p
- print p.generateChildren()
- print p 

This is the output. I have not included all of my source but as you can see the the move function works as needed. What I dont understand is why the generateChildren function not only doesnt seem to be creating any new Slide Puzzle Objects but it also messes with the puzzle state of the calling object.

- [1, 2, 3]
- [4, 'N', 5]
- [6, 7, 8]

- [1, 'N', 3]
- [4, 2, 5]
- [6, 7, 8]

- [None, None, None]

- [1, 2, 3]
- [4, 'N', 5]
- [6, 7, 8]

Upvotes: 1

Views: 147

Answers (2)

dav1d
dav1d

Reputation: 6055

Lists are passed by "reference", so you have to copy the list at first, otherwise your new Puzzle will operate on the same list:

def generateChildren(self):
    return [SlidePuzzle(self.puzzle_state[:]).move(m) for m in self.getValidMoves()]

Note the [:] which copies the list.

Furthermore .move returns None, that's why it ends up beeing None.

Upvotes: -1

chepner
chepner

Reputation: 532368

generateChildren returns a list of return values from SlidePuzzle.move(), not a list of SlidePuzzle objects. You don't show move, but I suspect it returns None.

Upvotes: 2

Related Questions