Python中的奇怪对象计数

时间:2017-02-21 11:08:30

标签: python class object

我正在尝试对象 - 我想要一个可以计算实例数量的对象。

我的代码:

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

由于

1 个答案:

答案 0 :(得分:1)

问题不在你的班级,而在你的网格中;您正在创建五个实例的相同列表的五个副本。

而是使用列表理解:

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