繁体   English   中英

为什么当我通过列表而不是浮点数或 integer 时,我的 class 实例在每次迭代后保存最终值?

[英]Why is my class instance saving the final value after each iteration when I pass through a list instead of a float or integer?

我想创建一个包含 function 的实例方法,该方法修改实例中的一个变量,然后多次迭代此操作。 这是我的代码示例:

class test:

    def __init__(self, counter):
        self.x = counter

    def func(self):
        self.x = self.x + 1


def routine(dat):
    t1 = test(dat)

    print('Initial Count: ', t1.x)

    for i in range(3):
        t1.func()

    print('Final Count: ', t1.x)

def main(dat):

    for i in range(3):
        print('Iter; ', i, 'Init Value: ', dat)
        routine(dat)
        print('Iter; ', i, 'Final Value: ', dat)

D = 0
main(D)

If I pass through the integer D to the method t1 and call the function func() three times, then the integer increases by 3. If I run this three times, as shown in the function main(), and do not change the variable dat 在迭代之间,则 dat 在迭代之间不会改变。 此外,变量 self.x 每次都会重置,如下所示:

最终结果 1

这按预期工作。

但是,如果我将 D 设置为包含 integer, D=[0]的列表,并相应地修改 function func() :

def func(self):
    self.x[0] = self.x[0] + 1

这样我就增加了列表中的值,然后 self.x 在迭代之间不会重置,似乎 function main() 中的变量 dat 现在表现得好像它是一个全局变量。 如果您运行此修改的代码,您会得到:

最终结果 2

为什么我的代码会这样? 我需要做什么才能使修改后的版本的行为与以前的版本相似? 我想通过一个数组,操作数组内部的值,output 结果,然后使用相同的初始条件再次执行此操作。

更新

感谢您的回复。 这种行为的原因是列表是可变的。 相反,我需要将 D 设置为元组并在方法内重新创建列表。 修改如下:

D = (0,)

def __init__(self, counter):
    self.x = [i for i in counter]

这是由于variable referencing机制而发生的。 让我们一步一步来 go。 我建议阅读我的一篇文章

case-1 D = 0 所以D是 integer。 整数是不可变的。

D = 0
A = D
A += 1
print(A) # it will print 1
print(D) # it will print 0

case-1 D = [0] D 是一个list 列表是可变的。

D = [0]
A = D
A[0] += 1
print(A) # it will print [1]
print(B) # it will print [1]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM