4

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.

2
  • I tried pie[2].x and pie[3].x every one prints the same 125 Commented Apr 10, 2017 at 13:03
  • 2
    They are class attributes not instance attributes Commented Apr 10, 2017 at 13:04

2 Answers 2

14

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
Sign up to request clarification or add additional context in comments.

1 Comment

To elaborate, use the self syntax instead of the class's name to assign values to an instance of the class.
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.