Junior — Middle
71
Quelles méthodes une classe doit-elle implémenter pour pouvoir être utilisée dans une construction with pour la gestion automatique des ressources?
Réponse de l'IA
sobes.tech IA
Для использования класса в конструкции with в Python он должен реализовать методы контекстного менеджера:
__enter__(self): вызывается при входе в блокwith. Обычно здесь происходит инициализация ресурса, и метод возвращает объект, который будет доступен внутри блока.__exit__(self, exc_type, exc_val, exc_tb): вызывается при выходе из блокаwith, даже если внутри блока возникло исключение. Здесь обычно освобождаются ресурсы или выполняется очистка.
Пример:
class FileManager:
def __init__(self, filename, mode):
self.filename = filename
self.mode = mode
def __enter__(self):
self.file = open(self.filename, self.mode)
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
self.file.close()
with FileManager('test.txt', 'w') as f:
f.write('Hello, world!')