Pythonclass打桩网之谜
Mystery of the piling grid in Python class
我正在设计一个在网格上玩的 Python 游戏。此网格由列表的列表表示 - 嵌套列表表示一行,该列表中的每个项目表示 "square".
示例:
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 中的变量。任何人都可以告诉我为什么我的可选参数列表不断堆叠来自 class 的先前实例调用的列表吗?
class Tictactoe:
def __init__(self, p, interactive=False, current_grid=[]):
然后它所做的就是询问用户网格大小并将列表附加到current_grid;我不明白为什么不同的实例调用会相互叠加。
Python 中的赋值不复制对象!请看看https://docs.python.org/2/library/copy.html
您可能需要使用 deepcopy
来复制您的列表列表。
我正在设计一个在网格上玩的 Python 游戏。此网格由列表的列表表示 - 嵌套列表表示一行,该列表中的每个项目表示 "square".
示例:
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 中的变量。任何人都可以告诉我为什么我的可选参数列表不断堆叠来自 class 的先前实例调用的列表吗?
class Tictactoe:
def __init__(self, p, interactive=False, current_grid=[]):
然后它所做的就是询问用户网格大小并将列表附加到current_grid;我不明白为什么不同的实例调用会相互叠加。
Python 中的赋值不复制对象!请看看https://docs.python.org/2/library/copy.html
您可能需要使用 deepcopy
来复制您的列表列表。