Python继承.无法读取属性



我对python来说很新,我正在尝试继承一个超类。

超类看起来像:

class LanguageModel:
    # Initialize and train the model (ie, estimate the model's underlying probability
    # distribution from the training corpus)
    def __init__(self, corpus):
        print("""Your task is to implement three kinds of n-gram language models:

    #enddef
    # Generate a sentence by drawing words according to the 
    # model's probability distribution
    # Note: think about how to set the length of the sentence 
    # in a principled way
    def generateSentence(self):
        print("Implement the generateSentence method in each subclass")
        return "mary had a little lamb ."
    #emddef

这是子类

class UnigramModel(LanguageModel):
    def __init__(self, corpus):
        print("Subtask: implement the unsmoothed unigram language model")
    #endddef
    def generateSentence(self):
        # Gets the total number of words in the corpus
        wordCount = 0
        for sentence in self.corpus:
            for word in sentence:
                wordCount += 1
        print(wordCount)

我首先尝试通过上述方法来获取语料库中的总词数,但它给了我一个错误,即当我尝试调用该函数时,它说" Unigrammodel'Object没有属性'corpus'。

<。

您必须如上所述声明语料库。或者,您可以将getter-stetter方法用于私有属性。

def init (self,corpus): self.corpus =语料库 @财产 def语料库(自我): 返回自我.__语料库 @setter def语料库(自我,价值): self .__ copus = value

最新更新