Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Apprendre Challenge: Class-based Resource Manager | Custom Context Managers
Python Context Managers

bookChallenge: Class-based Resource Manager

Imagine you are working on a Python application that interacts with a database. Every time you connect to the database, you want to ensure the connection is properly opened and closed, regardless of whether an error occurs during your operations. Rather than manually opening and closing the connection each time, you decide to use a context manager. By implementing a class-based context manager, as you have seen in previous lessons, you can automate the setup and teardown of the simulated database connection, making your code more robust and easier to maintain.

Tâche

Swipe to start coding

Implement a class-based context manager named DatabaseConnection that simulates managing a database connection. When entering the context, print "Connecting to database: <db_name>" where <db_name> is the value of the db_name attribute. When exiting the context, print "Disconnecting from database: <db_name>". Ensure that the class supports use with the with statement.

Solution

Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 3
single

single

Demandez à l'IA

expand

Demandez à l'IA

ChatGPT

Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion

close

Awesome!

Completion rate improved to 8.33

bookChallenge: Class-based Resource Manager

Glissez pour afficher le menu

Imagine you are working on a Python application that interacts with a database. Every time you connect to the database, you want to ensure the connection is properly opened and closed, regardless of whether an error occurs during your operations. Rather than manually opening and closing the connection each time, you decide to use a context manager. By implementing a class-based context manager, as you have seen in previous lessons, you can automate the setup and teardown of the simulated database connection, making your code more robust and easier to maintain.

Tâche

Swipe to start coding

Implement a class-based context manager named DatabaseConnection that simulates managing a database connection. When entering the context, print "Connecting to database: <db_name>" where <db_name> is the value of the db_name attribute. When exiting the context, print "Disconnecting from database: <db_name>". Ensure that the class supports use with the with statement.

Solution

Switch to desktopPassez à un bureau pour une pratique réelleContinuez d'où vous êtes en utilisant l'une des options ci-dessous
Tout était clair ?

Comment pouvons-nous l'améliorer ?

Merci pour vos commentaires !

Section 2. Chapitre 3
single

single

some-alt