实施具有以下属性的类Car。一辆车有一辆 一定的燃油效率(以英里/加仑计) 油箱中的燃油量。效率在中指定 构造函数,初始燃油油位为0.供应方法驱动 模拟驾驶汽车一定距离,减少 油箱中的燃油油位,以及方法getGasLevel,返回 当前的燃料水平,以及加油,加油。样品用法:
myHybrid = Car(50) myHybrid.addGas(20) myHybrid.drive(100) print(myHybrid.getGasLevel())
编写一个主程序来测试你的课程。
我的代码:
class Car(object):
def __init__(self, fuelEfficiency):
super(Car, self).__init__()
self.fuelEfficiency = fuelEfficiency
self.fuelLevel = 0 # In gallons
# Returns the amount of gas
def getGasLevel(self):
return self.fuelLevel
# Adds gas
def addGas(self, gasToAdd):
self.fuelLevel += gasToAdd
# Simulates driving car for a given distance
# and reduces the amount of gas based on the
# fuelEfficiency.
def drive(self, distanceInMiles):
gasToRemove = self.fuelEfficiency * distanceInMiles
self.fuelLevel -= gasToRemove
# Ensure we don't go below zero gas
self.fuelLevel = max(self.fuelLevel,0)
def main():
myHybrid=Car(50)
myHybrid.addGas(20)
myHybrid.drive(100)
print(myHybrid.getGasLevel())
答案 0 :(得分:0)
您实际上需要致电main()
在底部添加以下行(无缩进):
if __name__ == '__main__':
main()
答案 1 :(得分:0)
一些事情:
您不会调用main()
。我怀疑这是一个复制和粘贴错误。
你搞砸了减少燃料的数学。而不是self.fuelEfficiency * distanceInMiles
它应该是distanceInMiles / self.fuelEfficiency
。您当前的代码减去100 * 50加仑而不是12加仑。因此,显然,你的燃料将达到0。
class Car(object):
def __init__(self, fuelEfficiency):
super(Car, self).__init__()
self.fuelEfficiency = fuelEfficiency
self.fuelLevel = 0 # In gallons
# Returns the amount of gas
def getGasLevel(self):
return self.fuelLevel
# Adds gas
def addGas(self, gasToAdd):
self.fuelLevel += gasToAdd
# Simulates driving car for a given distance
# and reduces the amount of gas based on the
# fuelEfficiency.
def drive(self, distanceInMiles):
gasToRemove = distanceInMiles / self.fuelEfficiency
self.fuelLevel -= gasToRemove
# Ensure we don't go below zero gas
self.fuelLevel = max(self.fuelLevel,0)
def main():
myHybrid=Car(50)
myHybrid.addGas(20)
myHybrid.drive(100)
print(myHybrid.getGasLevel())
if __name__ == '__main__':
main()