0
我試圖用對象進行實驗 - 我想要一個可以計算實例數量的對象。在Python中奇怪的對象計數
我的代碼:
class Location:
count = 0
def __init__(self, column, row):
self.column = column
self.row = row
self.num = Location.count
Location.count += 1
def position(self):
print("Col: %i, Row: %i, Instance: %i" % (self.column, self.row, self.num))
# set up grid
grid = [[0]*5]*5
# Create objects in all positions
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
grid[i][j] = Location(i, j)
grid[i][j].position() #prints correctly
for i in range(0, len(grid)):
for j in range(0, len(grid[i])):
grid[i][j].position() #prints incorrectly -- WHY?!?!
爲什麼它,打印內容時電網的第二次,顯示出完全錯誤的數據?
我基本上是創建一個對象類的實例的網格。我能夠跟蹤此對象中的實例數量。
這段代碼並不適用於任何特別的東西 - 只是爲了我自己的享受和學習!
編輯**輸出編:
Col: 0, Row: 0, Instance: 0
Col: 0, Row: 1, Instance: 1
Col: 0, Row: 2, Instance: 2
Col: 0, Row: 3, Instance: 3
Col: 0, Row: 4, Instance: 4
Col: 1, Row: 0, Instance: 5
Col: 1, Row: 1, Instance: 6
Col: 1, Row: 2, Instance: 7
Col: 1, Row: 3, Instance: 8
Col: 1, Row: 4, Instance: 9
Col: 2, Row: 0, Instance: 10
Col: 2, Row: 1, Instance: 11
Col: 2, Row: 2, Instance: 12
Col: 2, Row: 3, Instance: 13
Col: 2, Row: 4, Instance: 14
Col: 3, Row: 0, Instance: 15
Col: 3, Row: 1, Instance: 16
Col: 3, Row: 2, Instance: 17
Col: 3, Row: 3, Instance: 18
Col: 3, Row: 4, Instance: 19
Col: 4, Row: 0, Instance: 20
Col: 4, Row: 1, Instance: 21
Col: 4, Row: 2, Instance: 22
Col: 4, Row: 3, Instance: 23
Col: 4, Row: 4, Instance: 24
Col: 4, Row: 0, Instance: 20
Col: 4, Row: 1, Instance: 21
Col: 4, Row: 2, Instance: 22
Col: 4, Row: 3, Instance: 23
Col: 4, Row: 4, Instance: 24
Col: 4, Row: 0, Instance: 20
Col: 4, Row: 1, Instance: 21
Col: 4, Row: 2, Instance: 22
Col: 4, Row: 3, Instance: 23
Col: 4, Row: 4, Instance: 24
Col: 4, Row: 0, Instance: 20
Col: 4, Row: 1, Instance: 21
Col: 4, Row: 2, Instance: 22
Col: 4, Row: 3, Instance: 23
Col: 4, Row: 4, Instance: 24
Col: 4, Row: 0, Instance: 20
Col: 4, Row: 1, Instance: 21
Col: 4, Row: 2, Instance: 22
Col: 4, Row: 3, Instance: 23
Col: 4, Row: 4, Instance: 24
Col: 4, Row: 0, Instance: 20
Col: 4, Row: 1, Instance: 21
Col: 4, Row: 2, Instance: 22
Col: 4, Row: 3, Instance: 23
Col: 4, Row: 4, Instance: 24
感謝
從未列出的名單上應用乘法,除非你完全知道會 –
請告訴我們輸出什麼。計算機輸出不是「不正確」。你認爲它「不正確」是「不正確的」。關於它。 – pltrdy
是的 - 我接受計算機打印我告訴它打印的內容。 > _ < –