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

Tarefa

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.

Solução

Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3
single

single

Pergunte à IA

expand

Pergunte à IA

ChatGPT

Pergunte o que quiser ou experimente uma das perguntas sugeridas para iniciar nosso bate-papo

close

Awesome!

Completion rate improved to 8.33

bookChallenge: Class-based Resource Manager

Deslize para mostrar o 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.

Tarefa

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.

Solução

Switch to desktopMude para o desktop para praticar no mundo realContinue de onde você está usando uma das opções abaixo
Tudo estava claro?

Como podemos melhorá-lo?

Obrigado pelo seu feedback!

Seção 2. Capítulo 3
single

single

some-alt