I have a class Bin that contains a list items as an instance variable. I need to create a list of Bin objects and then add data to their items lists. For some reason, all the Bins seem to be sharing the same items list, even though items is (AFAIK) not static. What's going on?
MWE:
import numpy as np
class Bin:
def __init__(self, items=[], left_edge=None, right_edge=None):
self.items = items
self.left_edge = left_edge
self.right_edge = right_edge
def add(self, item):
self.items.append(item)
# Create data
mean = 10.0
stdev = 2.0
sampsize = 10
data = np.random.normal(mean, stdev, sampsize)
# Create bins
bin_width = 0.5
bin_edges = np.arange(min(data), max(data) + bin_width, bin_width)
bins = []
print 'Before data add:'
for i in range(bin_edges.size-1):
bins.append(Bin(left_edge=bin_edges[i], right_edge=bin_edges[i+1]))
print id(bins[i].items)
# Actually put data in bins
indices = np.digitize(data, bin_edges[0:-1:1]) # need to cut off right edge
data_and_indices = np.array([data, indices]).T
print 'After data add:'
for pair in data_and_indices:
point = pair[0]
index = pair[1]
bins[int(index-1)].add(point)
print id(bins[int(index-1)].items)
print bins[int(index-1)].items