Python继承。无法读取属性

2024-09-28 22:19:13 发布

您现在位置: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”对象没有属性“corpus”


Tags: ofthetoinselfmodeldefcorpus
1条回答
网友
1楼 · 发布于 2024-09-28 22:19:13

您必须像上面提到的那样声明语料库。或者,您可以对私有属性使用getter setter方法

def init(self,corpus): self.corpus = corpus @property def corpus(self): return self.__corpus @setter def corpus(self, value): self.__corpus = value

相关问题 更多 >