首页 > 解决方案 > 以下情况如何正确使用抽象类

问题描述

我正在尝试实现一个代码来纠正给定单词中的小错别字。这些词是来自城市或州列表的专有名词。假设我们知道错字是来自一个城市还是一个州。我正在尝试实现两个类StateTypoCityTypo它们是基类的子类,BaseTypo.

这是BaseTypo和的代码StateTypo

from collections import Counter
from abc import ABC, abstractmethod


class BaseTypo(ABC):

    def __init__(self):
        self.WORDS = self.dictionary()
        self.N = sum(self.WORDS.values())

    @abstractmethod
    def dictionary(self):
        return dict()

    def known(self, words):
        """"""
        return set(w for w in words if w in self.WORDS)

    def P(self, word):
        """Calculate probability of the given word"""
        return self.WORDS[word] / self.N

    def correction(self, word):
        """Most probable word"""
        return max(self.candidates(word), key=self.P)

    def candidates(self, word):
        """ Generate possible correct words"""
        return self.known([word]) or self.known(self.edits1(word)) or self.known(self.edits2(word)) or [word]

    def edits1(self, word):
        letters = 'abcdefghijklmnopqrstuvwxyz'
        splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
        deletes = [L + R[1:] for L, R in splits if R]
        transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
        replaces = [L + c + R[1:] for L, R in splits if R for c in letters]
        inserts = [L + c + R for L, R in splits for c in letters]
        return set(deletes + transposes + replaces + inserts)

    def edits2(self, word):
        return (e2 for e1 in self.edits1(word) for e2 in self.edits1(e1))


class StateTypo(BaseTypo):
    def __init__(self):
        super(BaseTypo, self).__init__()
        self.address = 'states.txt'

    def dictionary(self):
        print(self.address)
        with open(self.address, 'r') as file:
            lines = file.readlines()
        lines = [line.strip() for line in lines]
        return Counter(lines)


if __name__ == '__main__':
    a = StateTypo()
    corrected = a.correction('himachal prfadesh')
    print(corrected) # should ideally print himachal pradesh

但是,上面的代码会遇到以下错误:

Traceback (most recent call last):
  File "correctTypo.py", line 59, in <module>
    corrected = a.correction('himachal prfadesh')
  File "correctTypo.py", line 25, in correction
    return max(self.candidates(word), key=self.P)
  File "correctTypo.py", line 29, in candidates
    return self.known([word]) or self.known(self.edits1(word)) or self.known(self.edits2(w
ord)) or [word]
  File "correctTypo.py", line 17, in known
    return set(w for w in words if w in self.WORDS)
  File "correctTypo.py", line 17, in <genexpr>
    return set(w for w in words if w in self.WORDS)
AttributeError: 'StateTypo' object has no attribute 'WORDS'

现在我知道我们真的不需要一个抽象类来实现它,但是考虑到我最初的想法是在基类中保留一个抽象方法,我该如何解决这个问题呢?

标签: pythonabstract-classabstract

解决方案


super意思是超级,它给你超级对象。

super(StateTypo, self).__init__()您可以通过or初始化基类BaseTypo.__init__(self),但不能super(BaseTypo, self).__init__()

并且address在初始化期间使用,所以它应该是

class StateTypo(BaseTypo):
    def __init__(self):
        self.address = 'states.txt'
        super(StateTypo, self).__init__()

或者您可以更改其他代码以__init__在第一行保留基类。


推荐阅读