Challenge: 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.
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ösung
Danke für Ihr Feedback!
single
Fragen Sie AI
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen
Awesome!
Completion rate improved to 8.33
Challenge: Class-based Resource Manager
Swipe um das Menü anzuzeigen
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.
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ösung
Danke für Ihr Feedback!
single