简体   繁体   中英

Python - List of objects (with list attribute)

This is part of my 'connect4' game code in python, where I try to create new nodes with different board setup.

class  node(object):
    def __init__(self, depth,board=None):
        if board is None:
            board = []
        self.board = board
        self.depth = depth

I define instance like that:

start = node(2,new_board)

Where new_board is list[7x6] filled with dots.

Afterwards I try to create child nodes with this function:

def child(depth, parent_board = []):
    children = [node(depth,[]) for x in range(7)]
    for x in range(7):
        y = 5
        while(y >= 0 and (parent_board[x,y] == 'O' or parent_board[x,y] == 'X')):
            y = y-1
        parent_board[x,y] = 'O'
        if (depth >=0):
            children[x] = node(depth-1, parent_board)
            children[x].board = parent_board
        parent_board[x,y] = '.'
    return children

The modification of parent board is correct, but whenever I try to pass it to my children in array, every single children receives the same array.

I understand that lists are mutable in python (that's why I used that 'None' thing in class __init__ function), but nevertheless I cant make every children to have different lists.

You can copy your list in node function, something like:

import copy

...

    self.board = copy.copy(board)

Details: https://docs.python.org/2/library/copy.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM