Sar*_*air 0 python inheritance overriding class python-3.x
我正在尝试编写一个类,用于文本操作.这个想法是类将支持基本的文本预处理,但如果有人想编写一个非常复杂的预处理函数,他们应该能够使用基类并覆盖它.我尝试了以下方式,即使我能以某种方式使其工作,我认为这不是正确的方法.
class TextPreprocessor:
def __init__(self, corpus):
"""Text Preprocessor base class.
corpus: a list of sentences
"""
self.corpus = corpus
self.word_tokens = [self.preprocess(sentence) for sentence in corpus]
def preprocess(self,sentence):
"""
strip each sentence , lowercase it and split by space # sentence.strip().lower().split()
"""
return sentence.strip().lower().split()
def preprocess_transform(self,sentence):
return self.preprocess(sentence)
Run Code Online (Sandbox Code Playgroud)
现在,如果我想编写一个新的预处理函数,这是最好的方法.我试过跟着,
class SubPreprocess(TextPreprocessor):
def __init__(self, corpus):
#### dummy preprocess function
def preprocess(self, sentence):
return sentence.strip().split() + ['HELLOOOOOOOOOOLLLL']
super.__init__(corpus)
Run Code Online (Sandbox Code Playgroud)
它不起作用.基本上我想要的是预处理函数(已修改),应该能够覆盖基类中的TextPreprocessor那个,这样当__init__调用它时self.word_tokens,应该基于新的预处理函数
以下将做:
class SubPreprocess(TextPreprocessor):
def preprocess(self, sentence):
return sentence.strip().split() + ['HELLOOOOOOOOOOLLLL']
Run Code Online (Sandbox Code Playgroud)
如果现在调用构造函数SubPreprocess,preprocess将使用新方法:
proc = SubPreprocess(some_corpus)
# looks up any methods in the mro of SubPreprocess
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41 次 |
| 最近记录: |