查找具有最高特定属性的实例

时间:2019-11-26 08:57:34

标签: python oop

这是汽车课。

我想找到cc最多的brand汽车。

  class car:

    category = 'auto'

    def __init__(self,brand,color,cc):
        self.brand = brand
        self.color = color
        self.cc = cc

def fastest(*args):
        return max(args)



nissanCar = car("Nissan","red",1800)
MercendesCar = car("Mercendes","gold",1600)
LamborghiniCar = car("Lamborghini","green",3000)

print(f"The fastest car is {fastest(nissanCar.cc,MercendesCar.cc,LamborghiniCar.cc)} cc and the its brand is ")

这将返回:

The fastest car is 3000 cc and its brand is

如何知道那辆车的品牌是什么?

2 个答案:

答案 0 :(得分:0)

我已经更新了您的代码,以便它可以显示多辆最快的汽车。最终可能会有数吨的汽车,并且可能有不止一辆具有相同cc的汽车。

如果您有任何问题,请在评论中让我知道。

欢迎堆栈溢出!

class car:

    category = 'auto'

    def __init__(self,brand,color,cc):
        self.brand = brand
        self.color = color
        self.cc = cc

def fastest(cars):
        max_cc = max([car.cc for car in cars])
        fastest_cars = [car for car in cars if car.cc == max_cc]
        return fastest_cars



NissanCar = car("Nissan","red",1800)
MercedesCar = car("Mercendes","gold",1600)
LamborghiniCar = car("Lamborghini","green",3000)

fastest_cars = fastest([NissanCar, MercedesCar, LamborghiniCar])
for fastest_car in fastest_cars:
    print(f"The fastest car is {fastest_car.brand} with {fastest_car.cc} cc")

答案 1 :(得分:0)

当前,您的“最快”功能只是包装了内置的“最大”功能。这不是很有用,因为它实际上使代码的可读性降低,只是查看您认为它做的事情更具体的名称。如果您只想返回最高抄送,则可以直接致电max。

但是,这仍然使您有问题。仅找到最大值cc,就失去了该cc值与car类的特定实例的关联。也许最好的解决方案是修改car类,以便您可以直接对类对象进行排序。

class car:
    category = 'auto'

    def __init__(self, brand, color, cc):
        self.brand = brand
        self.color = color
        self.cc = cc

    def __lt__(self, other):
        return self.cc < other.cc


NissanCar = car("Nissan","red",1800)
MercedesCar = car("Mercendes","gold",1600)
LamborghiniCar = car("Lamborghini","green",3000)

fastest_car = max([NissanCar, MercedesCar, LamborghiniCar])

print(fastest_car.brand, fastest_car.cc)