蟒蛇。使用继承编写代码以从经销商处查找汽车价格

时间:2018-03-02 17:52:34

标签: python python-3.x oop inheritance

我正在尝试使用继承来编写一个程序,其目标是确定汽车中车辆的价格为$ 4,000×车辆的车轮数量。你也买车。您可以提供车辆行驶里程的-10%的固定费率。固定费率为:汽车7,500美元,卡车:9,000美元。 输出的一个例子应该是:

>>> x=Car(4, 12000,'Mazda','CX5,2017,'Automatic','Red')
>>> y=Truck(7,8,15000,'Ford','Engine',1987)
>>> x.sale_price()
16000
>>> x.purchase_price()
6300.0
>>> x.getDescription()
'Mazda CX5 2017 -Red, 12000 miles >>> $16000'
>>> x.sell()
>>> x.sale_price()
0.0
>>> x.sell()
This item has been sold
>>> y.sale_price()
32000
>>> y.purchase_price()
7500.0
>>> y.getDescription()
'Ford Engine 1987, 15000 miles -7 seats >>> $32000'
>>> y.sell()
>>> y.sell()
This item has been sold
>>> y.sale_price()
0.0

我写了以下代码:

class Car:
   def __init__(self, wheels, miles, make, model, year):
      self.wheels = wheels
      self.miles = miles
      self.make = make
      self.model = model
      self.year = year
      self.sold_on = False

   def sell(self):
      if self.sold_on == True:
         print('This item has been sold')
      else:
         self.sold_on = True  

   def sale_price(self):
      if self.sold_on:
         return 0.0
      return 4000 * self.wheels 

   def purchase_price(self):
      return self.flat_rate - (0.10 * self.miles)

class Car(Car, object):
   def __init__(self, wheels, miles, make, model, year, gear, color):
      super(Car, self).__init__(wheels, miles, make, model, year)  
      self.gear = gear
      self.color = color
      self.flat_rate = 7500
   def getDescription(self):
      sale_price = self.sale_price()
      return '{} {} {} - {}, {} miles >>> ${}'.format(self.make, self.model, self.year, self.color, self.miles, sale_price)  

class Truck(Car, object):
   def __init__(self, wheels, miles, make, model, year, seats):
      super(Truck, self).__init__(wheels, miles, make, model, year)  
      self.seats = seats
      self.flat_rate = 9000

   def sale_price(self):
      if self.sold_on:
         return 0.0
      return 4000    

   def getDescription(self):
      sale_price = self.sale_price()
      return '{} {} {}, {} miles - {} seats >>> ${}'.format(self.make, self.model, self.year, self.miles, self.seats, sale_price)

我遇到了获得所需输出的问题。我觉得我的逻辑是正确的。我收到错误消息,上面写着“班级卡车的重复基础”,“已经定义了汽车类”。我不知道如何改变我的代码以消除这些。感谢您的帮助

1 个答案:

答案 0 :(得分:2)

class Vehicle(object):
    # Things

class Car(Vehicle):
    # other things

class Truck(Vehicle):
    # yet more things