简体   繁体   中英

Are Python class variables initialized before initialization of first class instance?

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()
    ...

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, ie, the body of the class definition.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM