Skip to main content
 首页 » 编程设计

python构造函数基础问题

2025年05月04日17kerrycode

我正在尝试重用在类的构造函数实例中声明的已打开文件,但我想我在做一些逻辑错误的事情。例如考虑以下示例

class Temp: 
    def __init__(self): 
        self.open_file_ = open('periodic_status','r') 
 
    def function1(self): 
        new_file = self.open_file_ 
        for i in new_file: 
            print 'test1' 
 
    def function2(self): 
        for j in self.open_file_: 
            print 'test2' 
 
if __name__ == '__main__': 
    obj1 = Temp() 
    obj1.function1() 
    obj1.function2() 

在上面的程序中,我可以打印 test1,但无法打印语句 test2。谁能给我解释一下逻辑。

谢谢

请您参考如下方法:

因为你的文件句柄已经用完了文件中的所有行。您需要使用以下方法在“function2”中倒带它:

f.seek(0) 

重新开始

请参阅此处 docs.python.org