0

In python 3.7, I'm trying to use an instance-specific list and for some reason, it behaves like a class attribute.

class Acc:
    def __init__(self, items = []):
        self.items = items

    def add(self, value):
        self.items.append(value)

Then I use

a = Acc()
b = Acc()
a.add(42)
print(b.items)

and get [42]. Why?

Peter Franek
  • 577
  • 3
  • 8
  • 25
  • 1
    Default arguments are evaluated *when the function is created*, not each time the function is called. You stored a single mutable object in the function defaults.. – Martijn Pieters Jun 23 '19 at 11:35
  • @MartijnPieters Honestly, I'm still confused.. I got the `def foo(a=[])` case from the link, but here it seems even a bit more strange. Is the `__init__` function "created" once, or twice, in my code? – Peter Franek Jun 23 '19 at 12:06
  • 1
    Just once. The `Acc()` call only **calls** it, indirectly (the `__new__` method is called and produces an instance object, then `__init__()` is called on that). Both times the `self.items` attribute is added which is a reference to the same list object. – Martijn Pieters Jun 23 '19 at 12:07
  • Note that `self.items = items` does not create a copy here. – Martijn Pieters Jun 23 '19 at 12:08

0 Answers0