I am trying to set the default variable of a class to some instance of another class which has its own default parameter. The problem I then face is that de setting of the parameter to the default does not seem to create a new instance.
Here is what I mean:
class TestA:
def __init__(self, x = 2):
self.x = x
class TestB:
def __init__(self, y = TestA()):
self.y = y
Now when I run
>>>> t = TestB()
I get what I expected: t.y.x = 2
. To the best of my understanding, what happened was that __init__
set t.y = TestA()
, and since TestA()
was called without arguments, it set t.y.x = 2
.
Finally I run t.y.x = 7
.
In the next step I do this:
>>>> s = TestB()
>>>> s.y.x
7
I expected that s.y.x == 2
.
Evermore so because when I just use TestA
, then
>>>> a = TestA()
>>>> a.x = 7
>>>> b = TestA()
>>>> b.x
2
How come it doesn't work as expected for t
and s
?
Also, how can I properly use a construction like this where the default for attribute y
is an instance of TestA
with the default for the attribute x
.