对于一个汽车品牌'VW'和三个模型,我想创建一个类Car
的单个实例,并且仅使用新模型更新其models
列表属性:
class Car(object):
cars = {}
def __init__(self, brand, model):
self.brand = brand
self.models = [model]
self.cars[brand] = self
def __new__(self, brand, model):
if brand in self.cars:
car = self.cars[brand]
if not model in car.models:
car.models.append(model)
print '....appended model %r to brand %r. result: %r' % (model, brand, car.getModels())
return car
else:
return super(Car, self).__new__(self, brand, model)
def getModels(self):
return self.models
cars = []
for i in range(3):
car = Car(brand='vw', model='model_%s' % i)
if not car in cars:
cars.append(car)
for car in cars:
print car.getModels()
所以,目标是print car.getModels()
打印:
['model_0', 'model_1', 'model_2']
相反,我只获得最后一个模型:['model_2']
代码中的错误在哪里?