Python类中打桩网格的奥秘

时间:2015-02-24 22:01:45

标签: python dictionary

我正在设计一个在网格上播放的Python游戏。此网格由列表列表表示 - 嵌套列表表示一行,该列表中的每个项目表示“正方形”。

示例:

t1 = tictactoe('p', True)
What size would you want your grid to be? 3
t1.current_grid
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
t2 = tictactoe('p', True)
What size would you want your grid to be? 3
t2.current_grid # now watch what happens
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]]
t1.current_grid # gets even weirder
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 2, 3], [4, 5, 6], [7, 8, 9]]

我没有使用全局变量;我只使用类中的变量。任何人都可以告诉我为什么我的可选参数列表会保持堆叠上一次实例调用的列表吗?

class Tictactoe:
      def __init__(self, p, interactive=False, current_grid=[]):

然后它只是询问用户网格大小并将列表附加到current_grid;我无法弄清楚为什么不同的实例调用相互堆叠起来。

1 个答案:

答案 0 :(得分:1)

Python中的赋值不会复制对象!请看https://docs.python.org/2/library/copy.html 您可能希望使用deepcopy复制列表列表。