Home >Backend Development >Python Tutorial >How Does Python's = Operator Differentially Affect Lists Depending on __iadd__ and __add__?

How Does Python's = Operator Differentially Affect Lists Depending on __iadd__ and __add__?

Susan Sarandon
Susan SarandonOriginal
2024-12-22 04:36:13403browse

How Does Python's  = Operator Differentially Affect Lists Depending on __iadd__ and __add__?

How the = Operator Operates on Lists in Python

The = operator in Python exhibits unexpected behavior when applied to lists. This behavior is attributed to the distinction between the iadd and add special methods.

iadd vs add

  • __iadd__': In-place addition; mutates the object being acted upon.
  • __add__': Returns a new object; used for the standard operator.

Behavior on Lists

When = is used on a list with an iadd method, the list is modified in place. If iadd is not defined, add is invoked, resulting in a new list.

Example

Consider the following code:

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)

f.bar += [3]
print(f.bar)
print(g.bar)

f.bar = f.bar + [4]
print(f.bar)
print(g.bar)

f = foo2(1)
g = foo2(2)
print(f.bar)
print(g.bar)

Output

[1, 2]
[1, 2]
[1, 2, 3]
[1, 2, 3]
[1, 2, 3, 4]
[1, 2, 3]
[1]
[2]

Explanation

  • foo implements __iadd__, so = modifies f.bar, causing it to affect all instances of foo.
  • foo2 lacks __iadd__, so = triggers __add__, returning a new list that replaces f.bar.
  • foo2 preserves its original bar list, while foo modifies it globally.

Conclusion

The behavior of = on lists depends on whether it calls iadd or add__. In-place modification occurs with __iadd__, while __add creates a new list.

The above is the detailed content of How Does Python's = Operator Differentially Affect Lists Depending on __iadd__ and __add__?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn