Классы в python

Вот такой код:

class Interpreter:
    def __init__(self, filename):
        self.code = open(filename)
        variables = {}
        with self.code as fp:
            self.lines = len(fp.readlines())
        self.current_line = 1

    def run(self):
        code = self.code
        while self.current_line <= self.lines:
            line = code.readline()
            print(f"Line {self.current_line}: {line}")
            self.current_line += 1



inter = Interpreter("programm.txt")
inter.run()

Должен с использованием класса вывести все строки поочередно в консоль.

Пример содержимого файла programm.txt:

line1
line2
line 3 
dmnvjsh

и тому подобное.

Проблема в чем. При запуске файла выдается такая ошибка:


Ответы (1 шт):

Автор решения: Mipsirint

self.code закрывается, как только оканчивается блок with self.code as fp:

Код лучше оформить так:

class Interpreter:
    def __init__(self, filename):
        self.file_name = filename
        variables = {}
        with open(filename) as code:
            self.lines = len(code.readlines())
        self.current_line = 1

    def run(self):
        with open(self.file_name) as code:
            while self.current_line <= self.lines:
                line = code.readline().replace("\n", "")
                print(f"Line {self.current_line}: {line}")
                self.current_line += 1



inter = Interpreter("programm.txt")
inter.run()
→ Ссылка