0
class Board: array = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] def reset(self): self.array = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]] class AI(Board): def __init__(self): self.array[0][0] = "X" ai = AI() board = Board() print(ai.array) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] print(board.array) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] ai.reset() print(ai.array) # [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] print(board.array) # [['X', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']] 

My question is why board.array is changed while ai.array was. If they are connected to each other, why both the attributes are not changed together while the method belongs to AI is run.

1 Answer 1

1

This can be understood in the following manner:

  • When you get self.array to use or modify it, as in the expression self.array[0][0] = "X", then

    • first the instance is checked to see if it has such an attribute;
    • if it does not, the type of the instance is checked for the attribute.

(this is a simplification of what happens, but its all you need to know for this case)

  • When you set an instance, as you do in the expression self.array = [...] you are setting the attribute directly on the instance

So in your example code:

print(ai.array) # ai does not have an array, Board.array is returned print(board.array) # board does not have an array, Board.array is returned ai.reset() # this adds an attribute to ai print(ai.array) # ai **does** have an array, it is returned print(board.array) # board does not have an array, Board.array is returned 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.