[英]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. 这是我在python中的“ connect4”游戏代码的一部分,在该代码中,我尝试使用不同的主板设置来创建新节点。
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. 其中new_board是由点组成的list [7x6]。
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. 我了解列表在python中是可变的(这就是为什么我在__init__
函数类中使用了“ None”东西的原因),但是我仍然不能使每个孩子都拥有不同的列表。
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 详细信息: https : //docs.python.org/2/library/copy.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.