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.