附加到列表会覆盖Python中对象的某些属性

时间:2014-03-23 05:15:33

标签: python

我正在尝试列出Sequence类的对象列表。但init_seqs [i] .seq对于所有列表都是相同的(因为init_seqs [i] .seq会覆盖init_seqs [i-1] .seq),其他属性保持不变。以下是我的代码。请让我知道我在哪里弄错了。

class Sequence(object):

def __init__(self, seq, make_span):
    self.seq=seq
    self.make_span=make_span

def getMake_span(self):
    return self.make_span

def __cmp__(self,other):
    other_makespan=other.getMake_span()
    if self.getMake_span()>other_makespan:
        return 1
    if self.getMake_span()<other_makespan:
        return -1
    else:
        return 0

class FlowShopGA(object):
....
....
def createPopultation(self):
    init_seqs=[]
    jobs=list(xrange(self.numJobs))
    for i in xrange(self.POPULATION_SIZE):
        random.shuffle(jobs)
        r = Sequence(jobs,self.calc_MakeSpan(jobs))
        init_seqs.append(r)
    sort_init_seqs = sorted(init_seqs, key=lambda Sequence: Sequence.make_span)
    self.seqs = sort_init_seqs[:self.EVOLVING_POPULATION_Size]

1 个答案:

答案 0 :(得分:3)

所有实例都传递相同的对象。先复制。

r = Sequence(jobs[:], self.calc_MakeSpan(jobs))