如何为不同的类建立相互的方法?

时间:2018-11-21 15:46:53

标签: python class inheritance

我想制作一个文本语料库(英语和乌克兰语)。我想通过“ Corpus.ENG_Lullabies”将作者传递给方法“ words”来获得语料库的单词。当我这样做时,我得到一个错误。我可以为两个类创建单独的方法,但功能相同。但是我想节省空间,所以我想通过从另一个类继承它来使用一个相互方法。但是我做错了。

代码如下:

s=' foo'
if [[ $s =~ " " ]]; then
    echo 'contains space'
else
    echo 'ok'
fi

错误:

class Lullaby:
    def __init__(self, title, author, words):
        self.title = title
        self.author = author
        self.words = words

class Functions:
    def __init__(self,Lullabies):
        def words(author=''):
            for i in Lullabies:
                if author in Lullabies.author:
                    print(Lullabies.words)
        self.words=words

class ENG():
    def __init__(self):
        Lullabies = [Lullaby('1','1',['word1','word2','word3']),Lullaby('2','2',['word4','word5','word6'])]
        self.words=Functions(Lullabies).words


class UA():
    def __init__(self):
        Lullabies = [Lullaby('1','1',['Слово1','Слово2','Слово3']),Lullaby('2','2',['Слово4','Слово5','Слово6'])]
        self.words = Functions(Lullabies).words

class Corpus():
    def __init__(self):
        self.ENG_Lullabies=ENG
        self.UA_Lullabies=UA

cor=Corpus()
print(cor.ENG_Lullabies.words('1'))

预期输出:

Traceback (most recent call last):
  File "D:/myproject/Lullaby Corpus/TEST.py", line 32, in <module>
    print(cor.ENG_Lullabies.words('1'))
AttributeError: type object 'ENG' has no attribute 'words'

1 个答案:

答案 0 :(得分:3)

您将分配给Corpus属性:

class Corpus():
    def __init__(self):
        self.ENG_Lullabies=ENG
        self.UA_Lullabies=UA

,但其余代码均应使用实例。调用类以创建实例:

class Corpus():
    def __init__(self):
        self.ENG_Lullabies = ENG()
        self.UA_Lullabies = UA()

我强烈建议您坚持使用Python's naming conventions,并将lower_case_with_underscores用于属性和局部变量,这样一来,当您拥有一个类以及何时应该使用一个实例时,就会更加清楚。

接下来,您应该使用 inheritance Functions引入方法(在这里我将其重命名以更好地反映基类的目的)。

您还希望将演示文稿与类功能分开;不要使用words方法进行打印。返回结果,然后在有意义的地方使用print()将这些结果转换为用户反馈。这样一来,您以后就可以使用相同的方法,例如将结果写入网络套接字或文件,或在GUI中显示它们:

class Lullaby:
    def __init__(self, title, author, words):
        self.title = title
        self.author = author
        self.words = words

class LullabiesCollection:
    def __init__(self, lullabies):
        self.lullabies = lullabies

    def words(self, author=''):
        """Return the words of lullabies, in a list

        When author is given, limit the search to lullabies by author substring.

        """
        result = []
        for lullaby in self.lullabies:
            if not author or author in lullaby.author:
                result.append(lullaby.words)
        return result

class EnglishLullabies(LullabiesCollection):
    def __init__(self):
        super().__init__([
            Lullaby('1', '1', ['word1', 'word2', 'word3']),
            Lullaby('2', '2', ['word4', 'word5', 'word6'])
        ])

class UkranianLullabies(LullabiesCollection):
    def __init__(self):
        super().__init__([
            Lullaby('1', '1', ['Слово1', 'Слово2', 'Слово3']),
            Lullaby('2', '2', ['Слово4','Слово5','Слово6'])
        ])

class Corpus():
    def __init__(self):
        self.eng = EnglishLullabies()
        self.ua = UkranianLullabies()

cor = Corpus()
for words in cor.eng.words('1'):
    print(words)

不是我认为CorpusEnglishLullabiesUkranianLullabies实际上需要是。仅在添加功能时才创建新类;当只是创建摇篮曲分组时,您不需要新的类。

以下内容也可以工作:

corpus = {
    'eng': LullabiesCollection([
        Lullaby('1', '1', ['word1', 'word2', 'word3']),
        Lullaby('2', '2', ['word4', 'word5', 'word6'])
    ]),
    'ua': LullabiesCollection([
        Lullaby('1', '1', ['Слово1', 'Слово2', 'Слово3']),
        Lullaby('2', '2', ['Слово4','Слово5','Слово6'])
    ]),
}
for words in corpus['eng'].words('1'):
    print(words)