__getitem __()是按字或字符分割的吗?

时间:2015-12-04 04:41:56

标签: python python-3.x

我正在上课,在课堂上我有一个__getitem__(),但是当我要求它在句子中返回一个单词时,它会返回该字母。

class Sentence():
    #initial attributes
    sentence = ""
    new_sentence = ''
    def __init__(self,new_sentence):
        self.sentence = new_sentence 
        self.word_list = new_sentence.split()# creates a word list
    def __str__(self):
        return self.sentence # return the original sentence
    def __add__(self,other):
        self.new_sentence = str(self.sentence)+ " " + str(other.sentence)
        return self.new_sentence
    def __getitem__(self,index):
        print('in getitem')
        return self.sentence[index]

def main():
    text1 = "I went home."
    text2 = "I got sleep."
    sentence1 = Sentence(text1)
    sentence2 = Sentence(text2)
    full_sentence = sentence1 + sentence2
    print(sentence1)
    print(full_sentence)
    print(sentence1[1])

print(sentence1[1])给了我一个空的空间。 此外,我想知道如何改变__getitem__(),以便如果我正确print(sentence1[0])print(sentence2[1])它将给我包含在full_sentence索引中的单词。

1 个答案:

答案 0 :(得分:0)

split()基于空格(单词)工作。但是,您无法访问其结果:您的__getitem__()方法会返回self.sentence[index]sentence是一个字符串,因此您将从字符串返回一个字符。我认为您打算在return self.word_list[index]__getitem__()。{/ p>

要回答标题中的问题:__getitem__()不会拆分任何内容。它通常只是访问你告诉它的任何东西。