Python 如何将父参数的值设置为子方法?
我有一个段落类:Python 如何将父参数的值设置为子方法?,python,oop,super,Python,Oop,Super,我有一个段落类: 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()
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()
当段落直接将text
作为参数获取时,子类从get\u from\u 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'
但是,这意味着删除super()的初始化。是否有其他解决方案不必删除super()。\uuuu init\uuuu?
或者这甚至不是使用继承的情况吗?我认为在这里创建对象时,还应该为filepath指定一个值
fp = FileParagraph("sample.txt")
您还应该为文件路径和文本输入一个值
乙二醇
错误来自于在设置
self.filepath
之前调用依赖于self.filepath
的get\u from\u file
方法。只需更改\uuuu init\uuuu
中两行的顺序即可解决此问题
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()
您正在调用
self.get\u from_file()
,然后再设置self.filepath
。由于self.get\u from\u file()
要求设置该成员变量,因此您会得到错误。顺便说一下,这与继承或翻译无关method@UnholySheep是的,这就是错误的原因。您是否建议将self.filepath=filepath
放在super()。\uuuu init\uuuuu(text=self.get\u from_file())
之前以解决此问题?是的,应该这样做work@UnholySheep你能把这个作为回答吗?我会投赞成票:)
fp = FileParagraph(text = "sample.txt", filepath = " ")
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()