【问题标题】:Python. Using inheritance to write code to find price of car from dealershipPython。使用继承编写代码从经销商处查找汽车价格
【发布时间】:2018-03-02 17:52:33
【问题描述】:

我正在尝试使用继承来编写一个程序,其目标是确定一个停车场中车辆的价格为 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)

我在获取所需输出时遇到问题。我觉得我的逻辑是对的。我收到错误消息说“类卡车的重复基地”,“类汽车已经定义”。我不知道如何更改我的代码以消除这些。感谢您的帮助

【问题讨论】:

  • 不能重复使用同一个类名Car(Car, object),基类应该继承自object,子类不需要
  • @BrendanAbel 您根本不需要从 python3 中的对象继承。
  • 关于从对象继承:以上评论都没有错。让您的基类继承自对象可能是个好主意,但这不是必需的。如果您选择这样做,子类也不应该从它继承。
  • @ChootsMagoots 基类继承自对象是什么意思。你的意思是让“Class car”从下一个类继承?
  • @BrendanAbel 那我该怎么办?

标签: python python-3.x oop inheritance


【解决方案1】:
class Vehicle(object):
    # Things

class Car(Vehicle):
    # other things

class Truck(Vehicle):
    # yet more things

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-31
    • 2010-09-17
    • 1970-01-01
    • 2018-06-12
    • 2019-04-19
    • 1970-01-01
    • 2018-07-24
    相关资源
    最近更新 更多