【发布时间】:2017-11-22 10:35:48
【问题描述】:
实现一个具有以下属性的类 Car。一辆车有一个 一定的燃油效率(以英里/加仑衡量)和一定的 油箱中的燃油量。效率在 构造函数,初始燃料水平为0。提供方法驱动 模拟驾驶汽车一定距离,减少 油箱中的燃料油位,以及 getGasLevel 方法,以返回 当前的燃油油位和 addGas 油箱。示例用法:
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())
【问题讨论】:
-
为什么你认为有一个“错误”?发生了什么事出乎你的意料?
-
你为什么把它标记为python-2.7和python-3.x?不能两者兼有。
-
对不起,我是一个完整的初学者,所以我只是尝试在两个版本上标记它
-
asongtoruin,我没有得到任何价值
-
你确定是你写的代码吗?如果你这样做了,你会感到惊讶的是,你的间距和 cmets 与这些家伙完全相同...github.com/MosheBerman/oop-1/blob/master/1.3/Car.py
标签: python python-2.7