如何在python中创建一个对象数组?

时间:2017-04-10 13:00:30

标签: python arrays object

当我在python中创建一个对象数组时,初始化为数组的值不是预期的

我定义的类是

class piece:
    x = 0
    y = 0
    rank = ""
    life = True
    family = ""
    pic = ""

    def __init__(self, x_position, y_position, p_rank, p_family):
        piece.x = x_position
        piece.y = y_position
        piece.rank = p_rank
        piece.family = p_family

当我初始化数组时

pie = []
pie.append(piece(25, 25, "p", "black"))
pie.append(piece(75, 25, "p", "black"))
pie.append(piece(125, 25, "p", "black"))

print(pie[1].x)

输出为125 其中预期产量为75

2 个答案:

答案 0 :(得分:10)

您正在设置类属性,而不是将值分配给类的实例:

class piece:

    def __init__(self, x_position, y_position, p_rank, p_family):
        self.x = x_position
        self.y = y_position
        self.rank = p_rank
        self.family = p_family

答案 1 :(得分:2)

您试图将值设置为静态的类变量。因此,该类的所有实例仅创建和共享一个副本。因此,只反映了最后一个值