1

我正在尝试模拟以下输出(来自 Marakana.com 的优秀 Python 教程

>>> 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函数,但是你如何为一个方法做到这一点?

4

2 回答 2

7

并不是方法是可迭代的;该方法返回的值是可迭代的。一个 cars_by_age实现可以简单地返回一个Cars 列表。

def cars_by_age(self):
    return sorted(self.cars, key=lambda car: car.year)

用于sorted创建新的排序列表,并用于lambda指定要按汽车year属性排序。

http://wiki.python.org/moin/HowTo/Sorting

于 2012-05-24T17:16:45.373 回答
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)
于 2012-05-24T22:46:57.303 回答