-
Notifications
You must be signed in to change notification settings - Fork 0
/
melons.py
96 lines (67 loc) · 2.2 KB
/
melons.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
86
87
88
89
90
91
92
93
94
95
96
"""Ubermelon melon types.
This provides a Melon class, helper methods to get all melons, find a
melon by id.
It reads melon data in from a text file.
"""
class Melon(object):
"""An Ubermelon Melon type."""
def __init__(self,
id,
melon_type,
common_name,
price,
image_url,
color,
seedless,
):
self.id = id
self.melon_type = melon_type
self.common_name = common_name
self.price = price
self.image_url = image_url
self.color = color
self.seedless = seedless
def price_str(self):
"""Return price formatted as string $x.xx"""
return "$%.2f" % self.price
def __repr__(self):
"""Convenience method to show information about melon in console."""
return "<Melon: %s, %s, %s>" % (
self.id, self.common_name, self.price_str())
def read_melon_types_from_file(filepath):
"""Read melon type data and populate dictionary of melon types.
Dictionary will be {id: Melon object}
"""
melon_types = {}
for line in open(filepath):
(id,
melon_type,
common_name,
price,
img_url,
color,
seedless) = line.strip().split("|")
id = int(id)
price = float(price)
# For seedless, we want to turn "1" => True, otherwise False
seedless = (seedless == "1")
melon_types[id] = Melon(id,
melon_type,
common_name,
price,
img_url,
color,
seedless)
return melon_types
def get_all():
"""Return list of melons."""
# This relies on access to the global dictionary `melon_types`
return melon_types.values()
def get_by_id(id):
"""Return a melon, given its ID."""
# This relies on access to the global dictionary `melon_types`
return melon_types[id]
# Dictionary to hold types of melons.
#
# Format is {id: Melon object, ... }
melon_types = read_melon_types_from_file("melons.txt")