我有一个类Bin
,它包含一个列表items
作为实例变量。我需要创建一个Bin
个对象列表,然后将数据添加到他们的items
列表中。出于某种原因,即使Bin
(AFAIK)不是静态的,所有items
似乎都在共享相同的items
列表。发生了什么事?
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