I have a Python class that takes an arguments to set the state of an object. This argument must be one option in a list of available options; for example, a traffic light can either be red, green or orange.
I have two approaches to handle this problem. I can use a string to set the state, but then I'll have to do additional error checking and it is unclear without looking at the code what states are available. Alternatively I can create a class that acts as an enum.
Which of these methods (or what other method) should I use?
Example with strings:
class Light(object):
def __init__(self, color):
self.color = color
def turn_on(self):
if self.color == 'red':
self.turn_on_red_light()
if self.color == 'green':
self.turn_on_green_light()
if self.color == 'orange':
self.turn_on_orange_light()
def turn_on_red_light():
# do stuff
return
def turn_on_green_light():
# do stuff
return
def turn_on_orange_light():
# do stuff
return
light = Light('red')
light.turn_on()
Alternative using simple "enum":
class Colors(object):
red, green, orange = range(3)
class Light(object):
def __init__(self, color):
self.color = color
def turn_on(self):
if self.color == Colors.red:
self.turn_on_red_light() # as above
if self.color == Colors.green:
self.turn_on_green_light() # as above
if self.color == Colors.orange:
self.turn_on_orange_light() # as above
light = Light(Colors.red)
light.turn_on()
Maybe this is not the best example as you can just call light.turn_on_red_light()
, but then that logic to decide what function to call must sit somewhere else. Let's pretend that is not an option.
I come across this situation often. Frequently I use it to define 'settings' within the class. I'd be interested to know what is the preferred method in Python or any other ways it can be improved?