0

I don't yet know how to find information in the Python docs when I need it. I would appreciate it if someone could point me to the section that addresses class variable initialization. I would like to know when class variables are initialized.

This is of interest to me because I have written a class that holds a single database connection in a class variable, so I would like to ensure that this connection is not opened until the first class instance is created.

I realize I could do this by initially setting the connection to None and then initializing it when the first instance is initialized, in its init method, but this seems more complicated than it should be. Am I safe with the following:

class DatabaseConnection:   
    connection = DB_API.makeConnection()
    ...
3
  • 3
    The class body gets executed when the class is defined so the connection will be created as soon as you import the module containing that class. Commented Oct 7, 2015 at 20:00
  • @tzaman thanks. mind telling me how you know this? Commented Oct 7, 2015 at 20:01
  • The tutorial is useful. You could also just try putting a print there and see what happens. Commented Oct 7, 2015 at 20:03

1 Answer 1

6

The documentation for class definitions says, as one of the steps in executing the class definition:

The class’s suite is then executed

(A "suite" is a code block, i.e., the body of the class definition.)

So the class body is executed right away when the class is defined.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.