Unexpected Behavior of = Operator on Lists
The = operator in Python exhibits unexpected behavior when operating on lists, as demonstrated in the following code snippet:
class foo: bar = [] def __init__(self, x): self.bar += [x] class foo2: bar = [] def __init__(self, x): self.bar = self.bar + [x] f = foo(1) g = foo(2) print(f.bar) print(g.bar)
Output:
[1, 2] [1, 2]
The = operator seems to affect every instance of the class, while foo = foo bar behaves as expected.
This behavior stems from the underlying implementation of the = operator. It first attempts to call the iadd special method, which is intended for in-place addition and modifies the object it acts on. If iadd is unavailable, it falls back to the add special method, which returns a new object.
In the case of lists, only add is defined, which returns a new list. Therefore, when = is used on a list, it creates a new list instead of mutating the existing list. This explains why f and g share the same bar list in the above example.
The = operator behaves differently for mutable objects, where it modifies them in-place through the iadd method. For immutable objects like strings and integers, only add is available, resulting in the creation of a new object.
To summarize:
The above is the detailed content of Why Does Python's = Operator on Lists Produce Unexpected Shared-State Behavior?. For more information, please follow other related articles on the PHP Chinese website!