0

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.

gebruiker
  • 115
  • 5
  • Because [the default value of a function is computed only once, when the `def` value is encountered](https://stackoverflow.com/questions/16549768/lifetime-of-default-function-arguments-in-python). – Stuart Dec 23 '22 at 22:45

1 Answers1

1

it's occours becouse the way dafault arguments work in Python.

You can use this approach:

class TestA:
    def __init__(self, x=2):
        self.x = x

class TestB:
    def __init__(self, y=None):
        if y is None:
            y = TestA()
        self.y = y
rzz
  • 77
  • 6