I’m trying to emulate the following output (from Marakana.com’s excellent Python tutorial:
>>> for c in lot.cars_by_age():
... print c
1981 VW Vanagon
1988 Buick Regal
2010 Audi R8
My code so far:
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)
I want to add a method (cars_by_age()) to the ParkingLot() class. However, this method somehow needs to be iterable, as per the sample code. I’m not sure how to do this – for a class, you define an iter function, but how do you do that for a method?
It’s not that the method is iterable; the value returned by the method is iterable. A
cars_by_ageimplementation could simply return a list ofCars.Use
sortedto create a new sorted list, and uselambdato specify that you want to sort by the car’syearattribute.http://wiki.python.org/moin/HowTo/Sorting