Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lära 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.

Uppgift

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.

Lösning

Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3
single

single

Fråga AI

expand

Fråga AI

ChatGPT

Fråga vad du vill eller prova någon av de föreslagna frågorna för att starta vårt samtal

close

Awesome!

Completion rate improved to 8.33

bookChallenge: Class-based Resource Manager

Svep för att visa menyn

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.

Uppgift

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.

Lösning

Switch to desktopByt till skrivbordet för praktisk övningFortsätt där du är med ett av alternativen nedan
Var allt tydligt?

Hur kan vi förbättra det?

Tack för dina kommentarer!

Avsnitt 2. Kapitel 3
single

single

some-alt