2017-02-21 13 views
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?!?! 

二回目のグリッドの内容を印刷するときに、なぜそれは、完全に間違ったデータを示していますか?

私は本質的にオブジェクトクラスのインスタンスのグリッドを作成しています。私は、このオブジェクトのインスタンスの数を把握できるようにしています。

このコードは特別なものではありません。自分の楽しみと学習のためだけです。

編集** CODE OF OUTPUT:

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 

おかげ

+0

あなたは完全に –

+0

は私たちに出力を表示してください期待するものを知っている以外、リストのリスト上の乗算を適用することはありません。コンピュータの出力が「正しくありません」。あなたは「間違っている」と誤って考えています。それについて。 – pltrdy

+0

はい - コンピュータが印刷するよう指示したものを印刷することを認めます。 > _ < –

答えて

1

問題は、あなたのクラスではありませんが、あなたのグリッドで。 5つのインスタンスの同じリストの5つのコピーを作成しています。

代わりにリストの内包表記を使用します。

grid = [[0]*5] for _ in range(5)] 
+0

ありがとうございました...完璧に働いています!私はそれがいつも同じリストを指していたのを見ることができたPythonの視覚化装置を使用しました、そして、私はなぜうまくいかないのですか?再度、感謝します! –