在python中打印类中的排序列表

时间:2017-05-10 09:23:04

标签: python

我正在尝试显示已排序的汽车列表并将其打印出来 - DisAllCarsSorted()。

这是我的代码(更正后):

class Car:

    def __init__(self, manufacture, production_year):
        self.manufacture = manufacture
        self.production_year = production_year

    def __str__(self):
        return '{} {}'.format(self.manufacture, self.production_year)

class CarOwner:

    car_owners = []
    all_cars = []

    def __init__(self, name):
        self.name = name
        self.cars = []
        CarOwner.car_owners.append(self)

    def add_car (self, car):
        self.cars.append(car)
        CarOwner.all_cars.append(car)


    def DisAllCars():

        for owners in CarOwner.car_owners:
            for car in owners.cars:
                print(car)

    def DisAllCarsSorted():

        print(sorted(CarOwner.all_cars, key=lambda x: x.manufacture))

print(CarOwner.all_cars)
def DisOwnerCars(car_owner):
    for car in car_owner.cars:
        print(car)

def DisAllOwnerCars():
    for owners in CarOwner.car_owners:
        print('Cars owned by {}:'.format(owners.name))
        for car in owners.cars:
            print(car)        


jane = CarOwner("Jane")
jane.add_car(Car("Mitsubishi", 2017))

bob = CarOwner("Bob")
bob.add_car(Car("Mazda", 2013))
bob.add_car(Car("BMW", 2012))

DisOwnerCars(jane)
DisAllOwnerCars()
CarOwner.DisAllCarsSorted()
CarOwner.DisAllCars()

这是错误打印:

[<__main__.Car object at 0x0000000009DBD358>, <__main__.Car object at 0x0000000009DBD320>, <__main__.Car object at 0x0000000009DBD278>]

我明白这条线路并不好:

CarOwner.all_cars.append(car)

print(sorted(CarOwner.all_cars, key=lambda x: x.manufacture))

但我不知道如何改变它。

2 个答案:

答案 0 :(得分:0)

要获得正确的印刷品:

print([ str(x) for x in sorted(CarOwner.all_cars, key=lambda x: x.manufacture) ])

答案 1 :(得分:0)

  

这是错误打印:

[<__main__.Car object at 0x0000000009DBD358>, <__main__.Car object at 0x0000000009DBD320>, <__main__.Car object at 0x0000000009DBD278>]

您的代码效果很好。您所看到的不是错误,而是Python表示其类不提供__repr__方法的实例的方式。该方法用于表示打印时的实例,例如,作为清单的一部分。

class Car:
    ...
    def __repr__(self):
        return 'Car(%r, %r)' % (self.manufacture, self.production_year)

输出:

[Car('BMW', 2012), Car('Mazda', 2013), Car('Mitsubishi', 2017)]