use*_*169 1 python oop iteration methods
我正在尝试模拟以下输出(来自Marakana.com的优秀Python教程:
>>> for c in lot.cars_by_age():
... print c
1981 VW Vanagon
1988 Buick Regal
2010 Audi R8
Run Code Online (Sandbox Code Playgroud)
我的代码到目前为止:
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)
Run Code Online (Sandbox Code Playgroud)
我想在ParkingLot()类中添加一个方法(cars_by_age()).但是,根据示例代码,此方法需要以某种方式迭代.我不知道怎么做 - 对于一个类,你定义一个iter函数,但是你如何为一个方法做到这一点?
并不是该方法是可迭代的; 方法返回的值是可迭代的.一个 cars_by_age实现可以简单地返回列表Car秒.
def cars_by_age(self):
return sorted(self.cars, key=lambda car: car.year)
Run Code Online (Sandbox Code Playgroud)
使用sorted创建一个新的排序列表,并使用lambda指定要通过汽车的排序year属性.
http://wiki.python.org/moin/HowTo/Sorting