problem
I tried to call the constructor of a class inside another class' constructor's parameter's default assignment, but I encountered this problem where the constructor isn't called correctly. What is happening here?
code explanation
The Bad
class is the case that doesn't work and the Good
class is an ugly work around to solve the problem. The value Base.i
is incremented for every time the constructor Base.__init__
is called, and as can be seen, it isn't incremented correctly for the o2
object, but it seems to be incremented correctly for each of o1
, o3
and o4
.
code
class Base:
i = 0
def __init__(self):
Base.i += 1
self.i = Base.i
class Bad:
def __init__(self, base = Base()):
self.base = base
class Good:
def __init__(self, base = None):
if base is None:
self.base = Base()
else:
self.base = base
if __name__ == "__main__":
o1 = Bad()
o2 = Bad()
print("Bad:")
print(f"o1.i: {o1.base.i}")
print(f"o2.i: {o2.base.i}")
o3 = Good()
o4 = Good()
print("Good:")
print(f"o3.i: {o3.base.i}")
print(f"o4.i: {o4.base.i}")
output
o1.i: 1
o2.i: 1
Good:
o3.i: 2
o4.i: 3