0

Consider the following code, test_class.py:

class TestClass:
    def __init__(self,Na,Nb):
        self.a = list(range(Na))
        self.b = list(range(Nb))

    def swapA(self):
        a = self.a
        b = self.b
        a,b = b,a
        assert a is self.b
        assert b is self.a

    def swapB(self):
        a = self.a
        b = self.b
        a,b = b,a
        assert a is self.b
        assert b is self.a

        #why is this necessary?
        self.a = a
        self.b = b

if __name__ == '__main__':
    tc = TestClass(2,3)
    print('len(tc.a) = %d, len(tc.b) = %d' % (len(tc.a),len(tc.b)))
    tc.swapA()
    print('after swapA(): len(tc.a) = %d, len(tc.b) = %d' % (len(tc.a),len(tc.b)))
    tc.swapB()
    print('after swapB(): len(tc.a) = %d, len(tc.b) = %d' % (len(tc.a),len(tc.b)))

The output I get from running this (python test_class.py) is:

len(tc.a) = 2, len(tc.b) = 3
after swapA(): len(tc.a) = 2, len(tc.b) = 3
after swapB(): len(tc.a) = 3, len(tc.b) = 2

I can't understand why swapA() doesn't update self.a and self.b members as I would expect.. despite the assertion passing. I would expect that the behaviour of swapA() and swapB() would be identical, but it's clearly not.

Any explanation here would be greatly appreciated.

science404
  • 101
  • 1

0 Answers0