Below is the code sample:
class Class1:
def __init__(self):
print('Printing from Class1 init')
self.val = 0
def __str__(self):
return f'value = {self.val}'
class Class2:
def __init__(self, val=Class1()):
print(f'Printing from Class2 init')
print(val)
self.count = val
print('**********')
a = Class2()
a.count.val += 1
print(a.count)
print('**********')
b = Class2()
b.count.val += 1
print(b.count)
print('**********')
c = Class2()
c.count.val += 1
print(c.count)
print('**********')
This generates below output:
Printing from Class1 init
**********
Printing from Class2 init
value = 0
value = 1
**********
Printing from Class2 init
value = 1
value = 2
**********
Printing from Class2 init
value = 2
value = 3
**********
Can anyone explain why Class1 is initialised only once even when three different objects of Class2 are being created?