Consider the following code
JavaScript
x
8
1
class Foo:
2
i = 1 # initialization
3
def __init__(self):
4
self.i += 1
5
6
t = Foo()
7
print(t.i)
8
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
1
15
15
1
print('Before Foo')
2
class Foo:
3
i = 1
4
print(f'Foo.i is now {i}')
5
6
def __init__(self):
7
print('Inside __init__')
8
self.i += 1
9
print(f'i is now {self.i}')
10
print('After Foo')
11
12
print('Before __init__')
13
foo = Foo()
14
print('After __init__')
15
which prints:
JavaScript
1
8
1
Before Foo
2
Foo.i is now 1
3
After Foo
4
Before __init__
5
Inside __init__
6
i is now 2
7
After __init__
8
Notice however, that your self.i += 1
does not modify the class attribute Foo.i
.
JavaScript
1
3
1
foo.i # This is 2
2
Foo.i # This is 1
3