【问题标题】:How to set value of parent argument to child method?如何将父参数的值设置为子方法?
【发布时间】:2020-04-18 16:14:53
【问题描述】:

我有一个段落类:

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()

虽然 Paragraph 直接将 text 作为参数,但子类从 get_from_file 方法生成 text

但是,我似乎无法调用继承的 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__?的另一种解决方案

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

【问题讨论】:

  • 你在设置self.filepath之前调用self.get_from_file()。因为self.get_from_file() 需要设置该成员变量,所以您会收到错误消息。顺便说一句,这与继承或translate 方法无关
  • @UnholySheep 是的,这就是错误的原因。您是否建议将self.filepath = filepath 放在super().__init__(text=self.get_from_file()) 之前以解决问题?
  • 是的,应该可以的
  • @UnholySheep 你能把它作为答案发布吗?我会赞成:)

标签: python oop super


【解决方案1】:

错误来自调用get_from_file 方法,该方法依赖于self.filepath,在设置self.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()

【讨论】:

    【解决方案2】:

    我认为您还应该在此处创建对象时为文件路径指定一个值

    fp = FileParagraph("sample.txt")
    

    您还应该输入文件路径的值以及文本 例如

    fp = FileParagraph(text = "sample.txt", filepath = "  ")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-25
      • 1970-01-01
      • 2020-04-12
      • 2011-06-25
      相关资源
      最近更新 更多