简体   繁体   中英

How to make an array of objects in Python?

When I tried to create an array of objects in Python the values initialised to the arrays are not as expected.

The class I defined is:

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

And when I initialise the array:

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)

the output is 125 where the expected output is 75.

You are setting the class attributes, instead of assigning values to an instance of the class:

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

You are trying to set values to the class variables which are static. Hence only one copy is created and shared by all instances of the class. Hence only the last value is reflected

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM