Respuesta :
Answer:
class Odometer():
def __init__(self, mileage=0, unit='miles'):
if mileage < 0:
raise ValueError('Mileage cannot be in negative')
self.mileage = mileage
if unit in ['miles', 'kilometers']:
self.units = unit
else:
raise ValueError("Miles and kilometer unit are allowed only")
def __repr__(self):
return self.__str__()
def __str__(self):
return 'Mileage: {:.1f} {}'.format(self.mileage, self.units)
def add(self, odometer, distance):
if odometer.units == self.units:
self.mileage = odometer.mileage + distance
elif self.units == 'miles':
self.mileage = odometer.mileage / 1.6 + distance
else:
self.mileage = odometer.mileage * 1.6 + distance
def subtract(self, odometer, distance):
if odometer.units == self.units:
self.mileage = odometer.mileage + distance
elif self.units == 'miles':
self.mileage = odometer.mileage / 1.6 - distance
else:
self.mileage = odometer.mileage * 1.6 - distance
honda_odometer = Odometer(100.56, 'miles')
print('Reading of Honda odometer:', honda_odometer)
new_odometer = Odometer(100, 'kilometers')
print('Reading of New odometer:', new_odometer)
new_odometer.add(honda_odometer, 10)
print('Reading of New odometer after adding honda odometer:', new_odometer)
new_odometer.subtract(honda_odometer,20)
print('Reading of New odometer after subtracting honda odometer:', new_odometer)
Explanation:
- Create a class only supports miles and kilometers as units .
- Create the add method that accepts an odometer, distance and adds it to the current object .
- Create the subtract method that accepts an odometer and distance and subtract it to the current object .