Python对象共享实例变量列表

时间:2017-02-03 08:07:31

标签: python list memory-address

我有一个类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

0 个答案:

没有答案