Reputation: 205
I'm struggling with understanding a piece of code that's part of a larger problem set. The code is as follows (Note that WordTrigger
is a subclass of Trigger
):
class WordTrigger(Trigger):
def __init__(self,word):
self.word=word
def isWordin(self, text):
text = [a.strip(string.punctuation).lower() for a in text.split(" ")]
for word in text:
if self.word.lower() in word.split("'"):
return True
return False
So line 5 does the job of stripping the text of punctuation and making it lowercase. The string.split(" ")
method creates a list of all the words in the text, splitting them and inserting blank spaces in between. The for-statement checks to see whether the 'word' is in the 'text'. So does it recognizes the variable 'word' from the constructor?
Does self.word.lower()
make the word that was initialized by the constructor all lowercase? And does the 'if'-conditional in the 'for' loop make sure the search for 'alert' words doesn't exclude words with apostrophes?
Upvotes: 3
Views: 148
Reputation: 42411
So does it recognizes the variable 'word' from the constructor?
No. Variables defined within a method are local to that method, and object attributes (like self.word
are not confused with local variables (like word
).
Does self.word.lower() make the word that was initialized by the constructor all lowercase?
No. Strings are immutable in Python. It returns a new string -- a lower-cased version of self.word
.
And does the 'if'-conditional in the 'for' loop make sure the search for 'alert' words doesn't exclude words with apostrophes?
Seems right to me.
Upvotes: 3
Reputation: 36506
1st Question: The for-statement checks to see whether the 'word' is in the 'text'. So does it recognizes the variable 'word' from the constructor?
The for statement's word
is a local variable and is not the same as self.word
. You can essentially replace that for loop with item
or any variable name if you like.
2nd Question: Does self.word.lower() make the word that was initialized by the constructor all lowercase?
No it doesn't because they are two different things. the word
local variable is each item in the list text
. and self.word
is the variable you pass in to the WordTrigger
object when you first instantiate it.
Upvotes: 2