首页 > 解决方案 > 如何将父参数的值设置为子方法?

问题描述

我有一个段落类:

from googletrans import Translator

class Paragraph:

    def __init__(self, text, origin_lang='en'):
        self.text = text
        self.origin_lang = origin_lang

    def translate(self, dest_lang='ne'):
        translator = Translator()
        translation = translator.translate(text = self.text,
                                           dest=dest_lang)
        return translation.text

我用它做了一个子类:

class FileParagraph(Paragraph):

    def __init__(self, filepath):
        super().__init__(text=self.get_from_file())
        self.filepath = filepath

    def get_from_file(self):
        with open(self.filepath) as file:
            return file.read()

当 Paragraphtext直接作为参数获取时,子类text从该get_from_file方法生成。

但是,我似乎无法调用继承的translate方法:

fp = FileParagraph("sample.txt")
print(fp.translate(dest_lang='de'))

这会引发错误:

Traceback (most recent call last):
  File "C:/main.py", line 66, in <module>
    fp = FileParagraph("sample.txt")
  File "C:/main.py", line 20, in __init__
    super().__init__(text=self.get_from_file())
  File "C:/main.py", line 25, in get_from_file
    with open(self.filepath) as file:
AttributeError: 'FileParagraph' object has no attribute 'filepath'

一种解决方案是将子类init更改为:

def __init__(self, filepath):
    self.filepath = filepath
    self.text = self.get_from_file()

但是,这意味着删除 super() 的初始化。是否有另一种解决方案而无需删除super().__init__?

或者这甚至不是利用继承的情况?

标签: pythonoopsuper

解决方案


错误来自调用get_from_file方法,该方法依赖于self.filepath, beforeself.filepath设置。只需更改两行的顺序即可__init__解决此问题

class FileParagraph(Paragraph):

    def __init__(self, filepath):
        # set member variable first
        self.filepath = filepath
        # then call super's init
        super().__init__(text=self.get_from_file())

    def get_from_file(self):
        with open(self.filepath) as file:
            return file.read()

推荐阅读