given the following code:
class GridSpace:
space = "e"
class GridRow:
space1 = GridSpace()
space2 = GridSpace()
space3 = GridSpace()
space4 = GridSpace()
space5 = GridSpace()
space6 = GridSpace()
space7 = GridSpace()
space8 = GridSpace()
space9 = GridSpace()
space10 = GridSpace()
spaceList = [space1, space2, space3, space4, space5, space6, space7, space8, space9, space10]
class Grid:
gridRow1 = GridRow()
gridRow2 = GridRow()
gridRow3 = GridRow()
gridRow4 = GridRow()
gridRow5 = GridRow()
gridRow6 = GridRow()
gridRow7 = GridRow()
gridRow8 = GridRow()
gridRow9 = GridRow()
gridRow10 = GridRow()
rowList = [gridRow1, gridRow2, gridRow3, gridRow4, gridRow5, gridRow6, gridRow7, gridRow8, gridRow9, gridRow10]
grid = Grid()
grid.rowList[0].spaceList[0].space = "s"
for x in grid.rowList:
rowWord = ""
for y in x.spaceList:
rowWord = rowWord + y.space + " "
print(rowWord)
I want to output a 10x10 grid of the e character, except the top left character which is supposed to be an s character. What instead happens is I am changing the class variable for the first element of every row list, instead of the instance variable of the first element of only the first row list. How do I make it change only the very first character into an s, and leave the other 99 characters an e?
This happens because the following statement is True
grid = Grid()
print(Grid.rowList[0].spaceList[0] is Grid.rowList[1].spaceList[0]) # outputs True
Here you can see that the First row's spaceList[0]
is the exact same as the second row's spaceList[0]
(they are referring to the same object and when one is changed the other is as well).
As you have already somehow guessed, you need to turn these into instance variables. But you'll have to do this 2 level deeps, meaning you'll have to apply this to both GridSpace
and GridRow
class GridSpace:
def __init__(self):
self.space = "e" # Now "e" is unique to every column
As well as
class GridRow:
def __init__(self):
self.spaceList = [GridSpace() for _ in range(10)]
Now the statement print(Grid.rowList[0].spaceList[0] is Grid.rowList[1].spaceList[0])
is indeed False
and your code runs fine
s e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e
e e e e e e e e e e