【发布时间】: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 你能把它作为答案发布吗?我会赞成:)