0

I am building a program which involves lots of objects stored in a list. In my simplified code below, I have changed it so that the objects are instances of class 'Person', with a people[] list used to store the values for two Person instances. The code is below.

class Person:

    age = 0

people = []

for i in range (0, 2):

    people.append(Person)

people[0].age = 10

people[1].age = 50

print(people[0].age, people[1].age)

I expect the first Person object ( people[0] ) to get 10 for its age parameter, and people[1] to get the value 50 for the same variable. However, both people[0] and people[1] get 50 when I run the code.

What have I done wrong here, and what can I do so that people[0] gets 10 and people[1] gets 50?

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
Ethan Wrightson
  • 149
  • 1
  • 5
  • 12
  • @PRMoureu I'm relatively new to programming. Could you tell me how to do that in a comment, or do I need to go to an in depth answer? – Ethan Wrightson Nov 01 '17 at 08:01
  • 2
    When you write `people.append(Person)`, you are actually appending a reference to the class `Person` itself to the list. And you then change twice the same class object. You can create *instances* that way: `people.append(Person())`. – Serge Ballesta Nov 01 '17 at 08:03
  • @ Jean-FrançoisFabre: I'm not sure that it is a duplicate. Here OP failed to create instances variable. But not sure that it is worth re-opening it either :-) – Serge Ballesta Nov 01 '17 at 08:06

0 Answers0