2015-06-24 99 views
0

我正在定義一個名爲'car'的類,我將它與一個對我的類運行一系列測試的文檔進行比較。但是,我收到錯誤,我不知道爲什麼。這是我的代碼。方法Drive應該採取汽車並將其移動指定的英里數。如果汽車能夠在給定的燃料量下達到所有的里程數,那麼汽車就會啓動並輸出英里數。如果它不能,它會達到最大的里程數。 addFuel方法應該爲汽車添加燃料,但是如果它溢出,它不會添加任何燃料,並且如果指定的參數不是整數,或者不是正值,則應該拋出異常。並且tripRange模塊應該給出車內的加侖數量,並確定您將行駛多少英里。下面我已經發布了我的代碼,然後是代碼來測試它。你可以幫我嗎?我很感激。面向對象的Python編程

#Define the class 


class Car(object): 

    def __init__(self,fuelEfficiency=0,fuelCapacity=0,fuelLevel=0,odometer=0): 
     self.setCar(fuelEfficiency,fuelCapacity,fuelLevel,odometer) 

    def setFuelEfficiency(self,newFuelEfficiency): 
     self.setCar(fuelEfficiency = newFuelEfficiency) 

    def setFuelCapacity(self,newFuelCapacity): 
     self.setCar(fuelCapactity = newFuelCapacity) 

    def setFuelLevel(self,newFuelLevel): 
     self.setCar(fuelLevel = newFuelLevel) 

    def setOdometer(self,newOdometer): 
     self.setCar(odometer = newOdometer) 

    def setCar(self,fuelEfficiency = None,fuelCapacity = None,fuelLevel = None,odometer = None): 
     if fuelEfficiency == None: 
      fuelEfficiency = self.getFuelEfficiency 

     if fuelCapacity == None: 
      fuelCapacity = self.getFuelCapacity 

     if fuelLevel == None: 
      fuelLevel = self.getFuelLevel 

     if odometer == None: 
      odometer = self.getOdometer 

     self.fuelEfficiency = fuelEfficiency 
     self.fuelCapacity = fuelCapacity 
     self.fuelLevel = fuelLevel 
     self.odometer = odometer 

    def drive(self,miles): 
     if miles < 0: 
      return ("The car is not driven") 

     milesDriven = miles/self.fuelEfficiency 

     if milesDriven < self.fuelLevel: 
      print("The car drove {} miles".format(miles)) 
     else: 
      if self.fuelLevel == 0: 
       print("The car drove 0 miles") 
      else: 
       newMiles = milesDriven * miles 
       print("The car drove {} miles".format(newMiles)) 

     self.fuelLevel = self.fuelLevel - milesDriven 
     self.odometer += miles 

    def getCar(self): 
     #Returns a tuple that has (FE,FC,FL,OD) 
     return (self.fuelEfficiency,self.fuelCapacity,self.fuelLevel,self.odometer)   


    def addFuel(self,num): 
     if type(num) == str: 
      raise KeyError("String valued enter, an integer was expected.") 
     if num < 0: 
      print("Sorry, you need to enter a postive number.") 
     if num + self.fuelLevel > self.fuelCapacity: 
      return self.fuelLevel 
     else: 
      return self.fuelLevel + num 

    def getFuelEfficiency(self): 
     return self.getCar()[0] 

    def getFuelCapacity(self): 
     return self.getCar()[1] 

    def getFuelLevel(self): 
     return self.getCar()[2] 

    def getOdometer(self): 
     return self.getCar()[3] 

    def tripRange(self): 
     numOfMiles = self.fuelEfficiency 
     return numOfMiles 

    def __str__(self): 
     FE = self.getFuelEfficiency() 
     FC = self.getFuelCapacity() 
     FL = self.getFuelLevel() 
     OD = self.getOdometer() 

     string = '{}:{}:{}:{}'.format(FE,FC,FL,OD) 
     return string 

而這裏的測試代碼:

from car import * 

def checkCar(car, expected, message): 
    global errorsFound 
    mpg, cap, level, odo = expected 
    if car.getFuelEfficiency() != mpg: 
     errorsFound = True 
     print(message + ': Error efficiency. Expected ' + str(mpg)) 
     print('\tCar:', car) 
    if car.getFuelCapacity() != cap: 
     errorsFound = True 
     print(message + ': Error capacity. Expected ' + str(cap)) 
     print('\tCar:', car) 
    if car.getFuelLevel() != level: 
     errorsFound = True 
     print(message + ': Error level. Expected ' + str(level)) 
     print('\tCar:', car) 
    if car.getOdometer() != odo: 
     errorsFound = True 
     print(message + ': Error odometer. Expected ' + str(odo)) 
     print('\tCar:', car) 

def checkNum(value, expected, message): 
    global errorsFound 
    if value != expected: 
     errorsFound = True 
     print(message + ': Error value. Expected {}. Got {}'.format(expected, value)) 

def main(): 
    c = Car(25, 15) 
    checkNum(c.tripRange(), 0, 'Test 1')  

    expected = (25, 15, 0, 0) 
    checkCar(c, expected, 'Test 2') 

    c.addFuel(-1) 
    checkCar(c, expected, 'Test 3') 

    c.addFuel(1000) 
    checkCar(c, expected, 'Test 4') 

    c.addFuel('doctor') 
    checkCar(c, expected, 'Test 5') 

    c.addFuel(0) 
    checkCar(c, expected, 'Test 6') 

    c.addFuel(15) 
    expected = (25, 15, 15, 0) 
    checkCar(c, expected, 'Test 7') 

    c.drive(50) 
    expected = (25, 15, 13, 50) 
    checkCar(c, expected, 'Test 8') 

    c.drive(100000) 
    expected = (25, 15, 0, 375) 
    checkCar(c, expected, 'Test 9') 

    c.drive(5) 
    expected = (25, 15, 0, 375) 
    checkCar(c, expected, 'Test 10') 

    c.addFuel(10) 
    expected = (25, 15, 10, 375) 
    checkCar(c, expected, 'Test 11') 

    c.drive(-1) 
    expected = (25, 15, 10, 375) 
    checkCar(c, expected, 'Test 12') 

    c.drive(0) 
    expected = (25, 15, 10, 375) 
    checkCar(c, expected, 'Test 13') 

    checkNum(c.tripRange(), 250, 'Test 14') 

    if not errorsFound: 
     print('No Errors Found') 



errorsFound = False 
main() 
+3

*我收到錯誤*什麼錯誤?有錯誤消息嗎?哪個測試用例失敗? –

+2

你得到什麼樣的錯誤?看起來有縮進錯誤,但它們可能是因爲你如何複製粘貼代碼到這裏。如果它們不是,請注意任何沒有縮進的def函數都在類的外面,因此不是一個方法,而是一個正常函數,即使它有一個「self」參數。 – Dleep

+0

這一切似乎運行良好,直到它到達addFuel方法。當測試文件給參數一個字符串時,我不知道如何拋出異常並移過它。另外,我只是得到錯誤的答案。這一切都有效,但我不知道我做錯了什麼來得到錯誤的答案。 –

回答

1

您的代碼按預期工作。 儘管我在car.py文件中發現了一些縮進錯誤,所以這可能是原因。具體爲__init__方法爲Car對象,你有def__init__(..),theres沒有空間。

如果你談論的是得到你的終端輸出拋出的異常:

Test 1: Error value. Expected 0. Got 25 
Sorry, you need to enter a postive number. 
Traceback (most recent call last): 
    File "/home/crispycret/Desktop/testcase.py", line 89, in <module> 
    main() 
    File "/home/crispycret/Desktop/testcase.py", line 42, in main 
    c.addFuel('doctor') 
    File "/home/crispycret/Desktop/car.py", line 64, in addFuel 
    raise KeyError("String valued enter, an integer was expected.") 
KeyError: 'String valued enter, an integer was expected.' 
[Finished in 0.1s with exit code 1] 

這是可以預期的。至於第42行的test.py中的main()函數的原因,您嘗試執行c.addFuel('doctor'),其中Car.addFuel()方法內的輸入類型是字符串時,您將引發KeyError("String valued enter, an integer was expected.")

順便提一下,你應該在引發錯誤時使用適當的例外,在這種情況下,你應該使用TypeError("String valued enter, an integer was expected.")來表示變量類型是錯誤的。

https://docs.python.org/2/tutorial/errors.html

1

Python是不是Java,所以不寫喜歡它。

吸氣劑和吸氣劑通常是不需要的,所以不要添加吸氣劑和吸氣劑,如果需要,以後可以隨時輕鬆使用。也沒有強制實例成員保護,但self._odometer中的下劃線向讀者表明_odometer是私有的。

放棄類型聲明並擁抱鴨子打字。在addFuel()中檢查參數是否爲str,如果不是,則繼續。但是,參數可以是文件,模塊,字典,列表等類型。你不能全部檢查它們,所以最好不要嘗試。

還剩下什麼,drive()被打破,但現在顯然是如此,因爲這麼多的垃圾已被刪除,tripRange()是多餘的。這留下了一種工作方法addFuel,並且很難對測試兩行簡單的代碼作出判斷。

class Car(object): 
    def __init__(self, efficiency=0, capacity=0, fuel=0, odometer=0): 
     self.efficiency = efficiency 
     self.capacity = capacity 
     self.fuel = fuel 
     self.odometer = odometer 

    # four useless setters removed 

def drive(self, miles): 
    # argument test removed 

    # miles/(miles/1 gallon) = miles * (1 gallon/miles) = 1 gallon 
    # so this expression and thus method are broken 
    one_gallon = miles/self.efficiency 

    if one_gallon < self.fuel: 
     print("The car drove {} miles".format(miles)) 
    elif self.fuel == 0: 
      print("The car drove 0 miles") 
    else: 
     newMiles = milesDriven * miles 
     print("The car drove {} miles".format(newMiles)) 

    self.fuel -= one_gallon 
    self.odometer += miles  

def addFuel(self, volume): 
    # Even more argument tests removed. 
    if volume + self.fuel <= self.capacity: 
     self.fuel += volume 

# The method "tripRange()" is equivalent to "car.efficiency" so is removed 

def __str__(self): 
    # trivial getters don't exist; the format template is now conventional 
    return '<Car {}, {}, {}, {}>'.format(self.efficiency, self.capacity, 
     self.fuel, self.odometer) 

您在測試中得到錯誤可能是因爲你的方法2/3被打破,甚至沒有考慮到特殊getCar()和所有的平凡的getter和setter方法。你需要寫的代碼比你少得多。