首页 > 解决方案 > 在 __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()

标签: python

解决方案


__init__()当你创建一个类实例(即类的对象)时,里面的代码就会被执行。尝试创建类的对象,例如:

test_process = InitProcess()

一旦执行此行,您的代码就会被执行。


推荐阅读