I'm trying to create a program that returns "emergency messages" using the Strategy Pattern. I'm building it in a more functional way in that instead of using abstract classes to define my functions, I just defined the functions and called those.
However, I get the error
TypeError: text_alarm() missing 1 required positional argument: 'message'
My code:
class EmergencyDrillBase(object):
_alarm_behavior = None
_suggested_message = None
def __init__(self, name, description):
self.name = name
self.description = description
def set_alarm_behavior(self, alarm_behavior):
self._alarm_behavior = alarm_behavior
def set_suggested_message(self, suggested_message):
self._suggested_message = suggested_message
# define alarm behaviors
def text_alarm(message):
print(f"This is a Text alarm with message: {message}")
# define suggested messages
def evacuate_message():
return("Evacuate")
# define drills
class FireDrill(EmergencyDrillBase):
_suggested_message = evacuate_message()
_alarm_behavior = text_alarm()
name = "Fire Drill"
description = "Fire Drill Description"
def __init__(self):
super(FireDrill, self).__init__(FireDrill.name, FireDrill.description)
def sound_alarm(self):
self._alarm_behavior(self._suggested_message)
def mini_drill_simulator():
fire_drill = FireDrill()
fire_drill.sound_alarm()
if __name__ == "__main__":
mini_drill_simulator()
Can anybody spot where my mistake is?
Expected outcome: print ("This is a Text alarm with message: Evacuate")
CodePudding user response:
I think that (at least)
_alarm_behavior = text_alarm()
should be _alarm_behavior = text_alarm
and
_suggested_message = evacuate_message()
should be _suggested_message = evacuate_message
and then the methods should be referred to as FireDrill._suggested_message
and FireDrill._alarm_behavior
.
So a problem is calling the method(s) instead of just referencing them.