简单的python类实现的意外输出

时间:2016-12-17 17:38:59

标签: python python-2.7

我不知道为什么这段代码说每个Car有两名乘客。我只在一辆车上添加一个Person。但是程序的输出就是这个。

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

我实际上只是期待爱丽丝能够驾驶A和比尔进入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()

1 个答案:

答案 0 :(得分:4)

这是因为person_list是一个类变量。

将其更改为实例级别,它将解决问题,即

class Car():

    def __init__(self, name):
        self.name = name
        self.person_list = []