Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are static variables initialized in Python?

Consider the following code

class Foo:
    i = 1 # initialization
    def __init__(self):
        self.i += 1

t = Foo()
print(t.i)

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

like image 748
David Avatar asked Mar 04 '23 01:03

David


1 Answers

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:

print('Before Foo')
class Foo:
    i = 1
    print(f'Foo.i is now {i}')
    
    def __init__(self):
        print('Inside __init__')
        self.i += 1
        print(f'i is now {self.i}')
print('After Foo')

print('Before __init__')
foo = Foo()
print('After __init__')

which prints:

Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__

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

foo.i # This is 2
Foo.i # This is 1
like image 189
Stephen C Avatar answered Mar 12 '23 12:03

Stephen C