为什么复制对象属性的更改会影响原始对象

时间:2020-07-03 03:25:50

标签: python attributes copy pass-by-reference

在处理作为对象的对象属性时遇到问题,因为当将它们放在变量上并更改了变量时,会影响原始对象。因此,我使用了copy,但是它有意想不到的行为。例如:

import copy

class AttrClassTest:
    def __init__(self, a):
        self.a = a

class ClassTest:
    def __init__(self, b):
        self.attr = b
 
atr_cl_t = AttrClassTest([1, 2, 3])
cl_t = ClassTest(atr_cl_t)
b = copy.copy(cl_t.attr)
c = b.a
c.append(4)
print(cl_t.attr.a)

所以问题是为什么尽管在下一行{{中使用[1, 2, 3, 4]语句时使用cl_t的副本却仍打印copy.copy(将4添加到原始对象) 1}}将打印c = b.a

0 个答案:

没有答案