-
Notifications
You must be signed in to change notification settings - Fork 59
/
07_oop_in_python_cars.py
85 lines (71 loc) · 1.89 KB
/
07_oop_in_python_cars.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#####################################
# Learn OOP by modeling cars
# --------------------------
# Learn OOP in python by modeling
# real world everyday objects.
#
#
# By Doug Purcell
# http://www.purcellconsult.com
#
#####################################
from random import choice
class Car:
"""
This class models a car in python.
"""
def __init__(self, year, make, model):
"""
Initializes the state of the car
object.
year: the year the car was manufactured.
make: the brand of the vehicle.
model: the name used by the manufacturer.
"""
self.year = year
self.make = make
self.model = model
self.speed = 0
self.colors = ['white', 'silver', 'black', 'grey',
'blue', 'red', 'brown', 'green']
self.car_color = choice(self.colors)
def get_year(self):
return self.year
def get_make(self):
return self.make
def accelerate(self, amount=5):
x = amount
if self.speed < 300 and x < 60:
self.speed += amount
else:
raise ValueError('Invalid Amount')
def hit_brakes(self, amount=5):
x = amount
if self.speed > 0 and x < 60:
self.speed -= amount
else:
raise ValueError('Invalid Amount')
def is_stopped(self):
if self.speed == 0:
return True
return False
def is_moving(self):
if self.speed > 0:
return True
else:
return False
def get_color(self):
return self.car_color
def speedometer(self):
return '{} mph'.format(self.speed)
a = Car('2010', 'Honda', 'Civic Hatchback')
print(a.speedometer())
print(a.is_moving())
print(a.is_stopped())
a.accelerate()
a.accelerate()
print(a.speedometer())
print(a.year)
print(a.get_color())
a.hit_brakes(10)
print(a.speedometer())