-1

Hello I was trying to debug an issue with some classes and I came to this minimal example:

class parentclass:
    a = ["a", "a"]
    b = ["b", "b"]

    def test(self, condition):
        c = self.a
        if condition:
            c += self.b
            # c = c + self.b
        print(c)


class childclass(parentclass):
    a = ["a_child", "a_child"]
    b = ["b_child", "b_child"]


child1 = childclass()

child1.test(condition=False)
child1.test(condition=True)
child1.test(condition=False)

Which yields to:

['a_child', 'a_child']
['a_child', 'a_child', 'b_child', 'b_child']
['a_child', 'a_child', 'b_child', 'b_child']

If I change the commented line:

class parentclass:
    a = ["a", "a"]
    b = ["b", "b"]

    def test(self, condition):
        c = self.a
        if condition:
            # c += self.b
            c = c + self.b
        print(c)


class childclass(parentclass):
    a = ["a_child", "a_child"]
    b = ["b_child", "b_child"]


child1 = childclass()

child1.test(condition=False)
child1.test(condition=True)
child1.test(condition=False)

It works as expected:

['a_child', 'a_child']
['a_child', 'a_child', 'b_child', 'b_child']
['a_child', 'a_child']

I though the operator += would make the same as in other languages like perl .=, where it adds the new variable to the original value.

But in this scenario it seems that this operation affects something outside the call of the function.

I was using python 3.10 when I tested this.

nck
  • 1,673
  • 16
  • 40
  • `c = self.a` assign reference to list `a` to local variable `c`, `c += self.b` append list `b` to list `a` which referenced through variable `c`. – Olvin Roght Jan 20 '22 at 14:36
  • https://nedbatchelder.com/text/names.html – chepner Jan 20 '22 at 14:37
  • `mylist += ...` mutates the list `mylist`. It is unfortunately not equivalent to `mylist = mylist + ...`. – khelwood Jan 20 '22 at 14:38
  • 1
    `+=` does add the new variable to the original value, but the original value is actually `self.a` not `c`. In your example `c` only points to `self.a` rather than having an independent `c`. – Eli Harold Jan 20 '22 at 14:38

1 Answers1

1

Long story short, there is a difference between these two operations, not only in lists, but for arrays, tensors and as far as I’m aware of also primitive types. For example:

a += 1

Will be translated into - go to where a is stored, and increment its value by 1

Whereas

a = a+1

a gets reassigned with the the value of a + 1, and is stored in a different address

sagi
  • 40,026
  • 6
  • 59
  • 84