python - 如何将父参数的值设置为子方法?
问题描述
我有一个段落类:
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__?
或者这甚至不是利用继承的情况?
解决方案
错误来自调用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()
推荐阅读
- python - 使用 Pandas Group By 将 JSON 列表展平为嵌套结构
- javascript - 如何获取带有 .jsk 扩展名的哈希键?
- google-chrome - 使用 iis 运行 snipe-it 并遇到 crbug/1173575,非 JS 模块文件已弃用问题
- python - Appium:从渲染器接收消息超时:在 Browserstack 中获取旧设备的屏幕截图时为 10.000
- android-studio - 如何通过 wifi-direct 发送应用程序的 recyclerview 列表
- node.js - Nginx Ingress Controller 在带有前缀路由的 Node.js 应用程序中出现错误
- java - 为什么它显示错误':app:checkDebugDuplicateClasses'
- ssh - 无法使用密钥文件“C:\GIT\HOME\.ssh\id_rsa”(OpenSSH SSH-2 私钥(新格式))
- java - 如何在导航视图的一侧添加可见箭头?
- android - Android中的“tob状态”是什么?