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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With