Począwszy od zdania klasy, staram się utworzyć wiele metod, które wydrukują wszystkie słowa w ciągu, zwróć słowo w indeksie i zastąpić słowo w indeksie (i więcej). Mam problemy ze zrozumieniem wykorzystania siebie w całej metodzie i wywołujące metody na końcu.

class Sentence:
    def __init__(self, sentence = ''):
        '''default value for private attribute (sentence) = empty string'''
        self._sentence_str = sentence
    def get_all_words(self):
        '''return all words in the sentence as a list'''
        self.s.split(" ")
        return self.s    
    def get_word(self, param):
        '''return only the word at a particular index'''
        '''arguments = index'''
        #Here, do I return an empty index so that I can call it/pick an index 
         at the end?
_sentence = Sentence("It feels like fall today")
print(_sentence)
index = self.index[2] #something like this? and print it?
0
szwack96 18 październik 2020, 06:45

1 odpowiedź

Najlepsza odpowiedź
    def __init__(self, sentence=''):
        
        '''default value for private attribute (sentence) = empty string'''
        self.sentence_str = sentence
    def get_all_words(self):
        '''return all words in the sentence as a list'''
        list = self.sentence_str.split(" ")
        return list    
        
    def get_word(self, index):
        '''return only the word at a particular index'''
        list = self.get_all_words() #split
        return list[index]  #this is how you access a list item by it's index: list[index]

    def replace_word(self, word, new_word):
        list = self.get_all_words()   # split
        current_word_index = list.index(word) #find in what index the word you want to change lives
        list[current_word_index] = new_word # replace the current word in current_word_index with the new word
        return ' '.join(list) #optional: you can return an actual string instead of a list, use return list if you want a list
        
        
sentence = Sentence("It feels like fall today")

print(sentence.get_all_words()) #this will return the string as a list
print(sentence.get_word(2)) # this will return an item at a certain index
print(sentence.replace_word('fall', 'summer')) #this will replace a word

Nie możesz po prostu zwrócić siebie.

0
Ahmed 18 październik 2020, 04:15