I'm fairly new to Python and so I'm not extremely familiar with the syntax and the way things work exactly. It's possible I'm misunderstanding, but from what I can tell from my code this line:
largeBoard = [[Board() for i in range(3)] for j in range(3)]
is creating 9 references to the same Board object, rather than 9 different Board objects. How do I create 9 different Board objects instead?
When I run:
largeBoard = [[Board() for i in range(3)] for j in range(3)]
x_or_o = 'x'
largeBoard[1][0].board[0][0] = 'g' # each Board has a board inside that is a list
for i in range(3):
for j in range(3):
for k in range(3):
for l in range(3):
print largeBoard[i][j].board[k][l]
I get multiple 'g' that is what made me think that they are all references to the same object.
The most Pythonic way to concatenate a list of objects is the expression ''. join(str(x) for x in lst) that converts each object to a string using the built-in str(...) function in a generator expression. You can concatenate the resulting list of strings using the join() method on the empty string as a delimiter.
The is keyword is used to test if two variables refer to the same object. The test returns True if the two objects are the same object. The test returns False if they are not the same object, even if the two objects are 100% equal. Use the == operator to test if two variables are equal.
We can create list of object in Python by appending class instances to list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C.
An object can contain the references to other objects.
You have it reversed: you are creating 9 independent Board
instances there. If you had something like
largeBoard = [[Board()] * 3] * 3
then you would only have a single instance. This is the root of a common mistake that many Python newcomers make.
[X for i in range(3)]
evaluates X
once for each i
(3 times here) whereas [X] * 3
evaluates X
only once.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With