为什么我的python变异?

时间:2015-08-30 10:30:34

标签: python

它可能很简单,但我不明白为什么boundary_tests在这里发生变异。

# initalise boundary tests used in other functions

def initialise_boundary_tests(self):

    self.boundary_tests = \
        [self.is_lowest(),
         self.is_highest(),
         self.is_leftmost(),
         self.is_rightmost()]

    self.b0 = self.boundary_tests[0]
    self.b1 = self.boundary_tests[1]
    self.b2 = self.boundary_tests[2]
    self.b3 = self.boundary_tests[3]

    self.set_inverse_bounds()

    if self.debugging:
        print("boundary test: " + str(self.boundary_tests))
        print("inverse boundary test: " + str(self.inverse_boundary_tests))

#initialise inverse results as results
def set_inverse_bounds(self):
    if self.debugging:
        print("setting inverse boundary tests")
        print("boundary test: " + str(self.boundary_tests))
    # self.inverse_boundary_tests = self.boundary_tests
    temp = self.boundary_tests
    self.inverse_boundary_tests = temp
    print("boundary test: " + str(self.boundary_tests))
    print("inverse boundary test: " + str(self.inverse_boundary_tests))
    for index in range(len(self.inverse_boundary_tests)):
        print("index" + str(index))
        if self.inverse_boundary_tests[index] != 0:
            print("before change: "+str(self.inverse_boundary_tests[index]))
            self.inverse_boundary_tests[index] = self.inverse_boundary_tests[index] * -1
            print(self.inverse_boundary_tests[index])
    self.i0 = self.inverse_boundary_tests[0]
    self.i1 = self.inverse_boundary_tests[1]
    self.i2 = self.inverse_boundary_tests[2]
    self.i3 = self.inverse_boundary_tests[3]

输出:

setting inverse boundary tests
boundary test: [1, -1, 0, 1]
boundary test: [1, -1, 0, 1]
inverse boundary test: [1, -1, 0, 1]
index0
before change: 1
-1
index1
before change: -1
1
index2
index3
before change: 1
-1
boundary test: [-1, 1, 0, -1]
inverse boundary test: [-1, 1, 0, -1]

1 个答案:

答案 0 :(得分:1)

set_inverse_bounds()中,self.boundary_teststempself.inverse_boundary_tests都指的是同一个列表。因此,当您修改self.inverse_boundary_tests中的值时,您将修改self.boundary_tests指向的相同列表。我不确定你为什么要temp,因为你在其他任何地方都没有使用它;除非你认为它会解决这个问题。

要制作副本,请使用:

self.inverse_boundary_tests = self.boundary_tests[:]

而不是:

temp = self.boundary_tests
self.inverse_boundary_tests = temp