I found what I believe it is a strange behavior. I'd like to know if it is indeed normal and I missed some important part of Python language.
Program:
class A():
def __init__(self, items=[]):
self.items = items
def append(self, item):
self.items.append(item)
a1 = A()
a2 = A()
a3 = A()
print('Before')
print('a1: %s' % a1.items)
print('a2: %s' % a2.items)
print('a3: %s' % a3.items)
a1.append('x')
print('After')
print('a1: %s' % a1.items)
print('a2: %s' % a2.items)
print('a3: %s' % a3.items)
Program output:
Before
a1: []
a2: []
a3: []
After
a1: ['x']
a2: ['x']
a3: ['x']
A new item appended to a single instance of "A" causes all instances of the same class being updated with same value.
I already solved by changing the definition of class "A" init:
class A():
def __init__(self, items=None):
if not items:
items = list()
self.items = items
but I would like to understand what is behind this behavior. Thanks in advance.