'Using inheritance to provide one class by another in Python
I'm trying to become a self taught developer, so I have nobody to ask when I do not understand the task in a course. The question is about inheritance.
Given structure
I have to implement some classes as a piece of program to monitor news. I was given the base abstract class Trigger
class Trigger(object):
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
# DO NOT CHANGE THIS!
raise NotImplementedError
And then I have to implement other classes accordingly the scheme. I did it like that:
class PhraseTrigger(Trigger):
def __init__(self, trigger, story):
self._trigger = trigger
self._story = story
def is_phrase_in(self):
phrase_to_match = r"((\W)+|^)"
for i in self._trigger.split():
phrase_to_match += i
if (i != self._trigger.split()[-1]):
phrase_to_match += r"(\W)+"
else:
phrase_to_match += r"((\W)+|$)"
# print(phrase_to_match) # delete after debugging
scheme_to_match = re.compile(phrase_to_match, re.IGNORECASE)
mo = scheme_to_match.search(self._story)
if (mo != None):
return True
else:
return False
def evaluate(self, story):
"""
Returns True if an alert should be generated
for the given news item, or False otherwise.
"""
if is_phrase_in(self):
return True
else:
return False
I've done all of them except Not-, And- and OrTrigger. Next I was said "The NotTrigger should produce its output by inverting the output of another trigger. The NOT trigger should take this other trigger as an argument to its constructor". How can I add another class to init method of NotTrigger? Or I did not catch the idea completely. Any advice will be appreciated. P.S. Sorry for long text and my poor English(it's my second language).
Solution 1:[1]
Let's start with a simple implementation of NotTrigger. Here is how you would define an initializer (technically not the constructor) that accepts another trigger:
class NotTrigger:
def __init__(self, trigger):
self.trigger = trigger
Now the evaluate method should be trivial:
def evaluate(self, story):
return not self.trigger.evaluate(story)
Hopefully you now see some of the problems with your implementation of PhraseTrigger:
PhraseTriggershould not accept neither another trigger as an argument to__init__, nor the story.PhraseTriggershould not directly implementevaluate: that's up to the child classes.PhraseTriggershould accept a phrase to search for.PhraseTriggershould provide a methodis_phrase_in(self, text)to search forself.phraseintext. Child classes will determine what to pass in fortext.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mad Physicist |
