I am working on a problem set for a Python class. We are being introduced to Classes. I am trying to (A) create a class called Sentence with a single parameter, string, and to create an instance variable that stores the sentence as a string. (B) Then to assign accessor methods for the class: getSentence(return the sentence as a string), getWords(return the list of words in the sentence), getLength(return the number of characters in the sentence), and getNumWords(return the number of words in the sentence). Below is what I have attempted thus far:
line = "This Tuesday is Election Day"
class Sentence:
def __init__(self, text, string, words, length, num):
self.text = sentence
self.string = str(self.text)
self.words = self.text.split()
self.length = len(self.text)
self.num = len(self.words)
def getSentence(self):
return self.string
def getWords(self):
return self.words
def getLength(self):
return self.length
def getNumWords(self):
return self.num
line.getWords()
Thank you for your time.
Below is the updated code that works:
class Sentence:
def __init__(self, string):
self.astring = str(string)
def getSentence(self):
return self.astring
def getWords(self):
return (self.astring).split()
def getLength(self):
return len(self.astring)
def getNumWords(self):
return len(self.getWords())
string = Sentence("The Election is tomorrow")
print (string.getSentence())
print (string.getWords())
print (string.getLength())
print (string.getNumWords())
line.getSentence()I receive "AttributeError: 'str' object has no attribute 'getSentence'"foo = Sentence(line). That will fail becauseSentence.__init__needs a bunch of variables. Butstring, words, length, numare calculated by the class so you shouldn't pass them into the initializer. So take them out. Then you get to the next problem.... This is called "test driven development". Write tests that break, fix the problem, write more tests.