python - 在 __init__ 函数中读取类中的文件不起作用
问题描述
我正在尝试在 python 中使用open()
. 下面是一个可以工作的小片段(Snippet - 1),但是当将相同的工作逻辑放入类和__init__()
函数中时,相同的函数停止工作并且不生成输出但也没有错误消息,只是用退出代码完成执行0。
您能否帮助确定 Snippet-2 的问题?我假设open()
不喜欢从__init__()
. 提前致谢。
#片段 - 1
f = open("file.txt", 'r')
for line in f:
print(line)
#片段 - 2
class InitProcess:
def __init__(self):
self.count = 0
filepath = "file.txt"
try:
self.fd = open(filepath)
for line in self.fd:
print(line)
finally:
self.fd.close()
解决方案
__init__()
当你创建一个类实例(即类的对象)时,里面的代码就会被执行。尝试创建类的对象,例如:
test_process = InitProcess()
一旦执行此行,您的代码就会被执行。
推荐阅读
- sql - BigQuery Pivot 数据行列(在标准 SQL 中,无硬编码)
- amazon-web-services - AWS Redshift 跨账户访问
- unity3d - 如何从 Unity 中的 Animated Tile/Tilemap.animationFrameRate 获取当前帧
- javascript - 如何在当前未悬停的所有其他图像上显示图像叠加层?
- browser - 无法识别有关 snapinsPage 的本地存储项目
- javascript - 在 Angular 中将一个数组类转换为另一个数组类
- applescript - 升级到 Catalina 后无法在 AppleScript 中获取智能相册
- c++ - 花括号内的结构声明
- angular - JUnit 测试用例出错。“没有找到测试运行器'JUnit'的测试
- r - 从其他多列的值有条件地替换多列的值