Skip to content

Commit e972e7f

Browse files
committed
change parts_factory fn to PartsFactory class (p179)
along the way converting the function into a static method and splitting the create part bit into a separate method. Also put the Part class inside PartsFactory to discourage anyone using the Part class directly (though we keep it for its __unicode__ method)
1 parent 70cb2c9 commit e972e7f

File tree

1 file changed

+25
-21
lines changed

1 file changed

+25
-21
lines changed

bike.py

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -77,28 +77,32 @@ def spares(self):
7777
return [part for part in self.parts if part.needs_spare]
7878

7979

80-
class Part(object):
81-
82-
def __init__(self, **kwargs):
83-
self.name = kwargs['name']
84-
self.description = kwargs['description']
85-
self.needs_spare = kwargs.get('needs_spare', True)
86-
87-
def __unicode__(self):
88-
uni = "%s: %s" % (self.name, self.description)
89-
if self.needs_spare:
90-
uni += " (needs spare)"
91-
return uni
92-
93-
94-
def parts_factory(config, part_class=Part, parts_class=Parts):
95-
return parts_class([
96-
part_class(
80+
class PartsFactory(object):
81+
class Part(object):
82+
def __init__(self, **kwargs):
83+
self.name = kwargs['name']
84+
self.description = kwargs['description']
85+
self.needs_spare = kwargs['needs_spare']
86+
87+
def __unicode__(self):
88+
uni = "%s: %s" % (self.name, self.description)
89+
if self.needs_spare:
90+
uni += " (needs spare)"
91+
return uni
92+
93+
@staticmethod
94+
def build(config, parts_class=Parts):
95+
return parts_class([
96+
PartsFactory._create_part(part_config) for part_config in config
97+
])
98+
99+
@staticmethod
100+
def _create_part(part_config):
101+
return PartsFactory.Part(
97102
name=part_config[0],
98103
description=part_config[1],
99104
needs_spare=part_config[2] if len(part_config) > 2 else True
100-
) for part_config in config
101-
])
105+
)
102106

103107

104108
class Bicycle(SchedulableMixin, object):
@@ -152,14 +156,14 @@ def spares_to_string(spares):
152156
print Gear(chainring=52, cog=11, wheel=wheel).gear_inches()
153157
print Gear(chainring=52, cog=11).ratio()
154158

155-
road_parts = parts_factory(road_config)
159+
road_parts = PartsFactory.build(road_config)
156160
road_bike = Bicycle(
157161
size='M',
158162
parts=road_parts)
159163
print road_bike.size
160164
print spares_to_string(road_bike.spares())
161165

162-
mountain_parts = parts_factory(mountain_config)
166+
mountain_parts = PartsFactory.build(mountain_config)
163167
mountain_bike = Bicycle(
164168
size='L',
165169
parts=mountain_parts)

0 commit comments

Comments
 (0)