Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 910
Vidhyanshu jain Avatar asked Sep 16 '25 16:09

Vidhyanshu jain


1 Answers

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
like image 142
Mike Scotty Avatar answered Sep 19 '25 04:09

Mike Scotty