Python继承。无法读取属性
问题描述:
我对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”对象没有属性'语料库'
答
您必须声明如上所述的语料库,或者您可以使用getter-setter方法私人属性的ods。
DEF 初始化(个体,胼): self.corpus =语料库 @property DEF语料库(个体): 返回自.__语料库 @Setter DEF语料库(个体,值): 自我.__语料库=值
'def __init __(self,corpus):'add'self.corpus = corpus'之后。 –