0

I dont know why this code is saying that each Car has two passengers. I am only adding one Person to one car. However the output of the program is this.

People in car A
Alice
Bill
People in car B
Alice
Bill

I am actually expecting only Alice to be in car A and Bill to be in car B.

class Car():

    name = None
    person_list = []

    def __init__(self, name):
        self.name = name

    def add_person(self, person):
        self.person_list.append(person)

    def list_people_in_car(self):
        print "People in car {}".format(self.name)
        for p in self.person_list:
            print p.name

class Person():

    name = None

    def __init__(self, name):
        self.name = name

if __name__ == '__main__':

    person_alice = Person('Alice')
    person_bill = Person('Bill')

    car_a = Car('A')
    car_a.add_person(person_alice)

    car_b = Car('B')
    car_b.add_person(person_bill)

    car_a.list_people_in_car()
    car_b.list_people_in_car()
Danny Cullen
  • 1,782
  • 5
  • 30
  • 47

1 Answers1

4

It is because person_list is a class variable.

Change it to instance level and it will fix the issue i.e.

class Car():

    def __init__(self, name):
        self.name = name
        self.person_list = []
Anthony Kong
  • 37,791
  • 46
  • 172
  • 304