-
Notifications
You must be signed in to change notification settings - Fork 0
/
car.py
30 lines (25 loc) · 896 Bytes
/
car.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# CP1404 Car class example
class Car:
def __init__(self, name="", fuel=0):
""" initialise a Car instance
fuel: float, one unit of fuel drives one kilometre """
self.name = name
self.fuel = fuel
self.odometer = 0
def add_fuel(self, amount):
""" add amount to the car's fuel"""
self.fuel += amount
def drive(self, distance):
""" drive the car a given distance if it has enough fuel
or drive until fuel runs out
return the distance actually driven """
if distance > self.fuel:
distance = self.fuel
self.fuel = 0
else:
self.fuel -= distance
self.odometer += distance
return distance
def __str__(self):
""" returns a formatted string """
return "{}, fuel={}, odometer={}".format(self.name, self.fuel, self.odometer)