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

Oppgave

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

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 3
single

single

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

close

Awesome!

Completion rate improved to 8.33

bookChallenge: Class-based Resource Manager

Sveip for å vise menyen

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.

Oppgave

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 desktopBytt til skrivebordet for virkelighetspraksisFortsett der du er med et av alternativene nedenfor
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 3
single

single

some-alt