我正在尝试模拟以下输出(来自Marakana.com的excellent Python tutorial:
>>> for c in lot.cars_by_age():
... print c
1981 VW Vanagon
1988 Buick Regal
2010 Audi R8
到目前为止我的代码:
class ParkingLot(object):
def __init__(self, spaces, cars=[]):
self.spaces = spaces
self.cars = cars
def park(self, car):
if self.spaces == 0:
print "The lot is full."
else:
self.spaces -= 1
self.cars.append(car)
def __iter__(self):
return (car for car in self.cars)
class Car(object):
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
return '%s %s %s' % (car.year, car.make, car.model)
我想在ParkingLot()类中添加一个方法(cars_by_age())。但是,根据示例代码,此方法需要以某种方式迭代。我不确定如何做到这一点 - 对于一个类,你定义了一个 iter 函数,但是你如何为一个方法做到这一点?
答案 0 :(得分:7)
方法不是可迭代的;方法返回的值是可迭代的。 cars_by_age
实施可以简单地返回Car
s的列表。
def cars_by_age(self):
return sorted(self.cars, key=lambda car: car.year)
答案 1 :(得分:0)
from operator import attrgetter
class ParkingLot(object):
def __init__(self, spaces, cars=None):
self.spaces = max(spaces, 0)
self.cars = cars or []
def park(self, car):
if self.spaces > 0:
self.spaces -= 1
self.cars.append(car)
else:
print "The lot is full."
def __iter__(self):
return iter(self.cars)
def cars_by_age(self):
return sorted(self.cars, key=attrgetter("year"), reverse=True)
class Car(object):
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def __str__(self):
return "{} {} {}".format(self.year, self.make, self.model)