Skip to content
Advertisement

When are static variables initialized in Python?

Consider the following code

JavaScript

When exactly does the initialization of i take place? Before the execution of the init method or after it?

Advertisement

Answer

Before.

The __init__ method isn’t run until Foo is instantiated. i=1 is run whenever the class definition is encountered in the code

You can see this by adding print statements:

JavaScript

which prints:

JavaScript

Notice however, that your self.i += 1 does not modify the class attribute Foo.i.

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement