# -*- coding: utf-8 -*-
import copy
# 序列
class TestCopy(object):
def testFunc2(self, xList, y):
xListCopy = copy.copy(xList)
yCopy = copy.copy(y)
yCopy = 1
xListCopy.append(5)
print("② testFunc2打印xList地址:", id(xList))
print("② testFunc2打印y地址:", id(y))
print("② testFunc2打印xListCopy地址:", id(xListCopy))
print("② testFunc2打印yCopy地址:", id(yCopy))
print("② testFunc2打印xListCopy值:", xListCopy)
# 主函数
if __name__ == "__main__":
print("▼ 测试copy操作 ▼")
testCell = TestCopy()
xList = [1, 2, 3, 4]
y = 0
print("① 执行函数前:")
print("① 打印xList值:", xList)
print("① 打印y值:", y)
print("① 打印xList地址:", id(xList))
print("① 打印y地址:", id(y))
testCell.testFunc2(xList, y)
print("③ 执行函数后:")
print("③ 打印xList值:", xList)
print("③ 打印y值:", y)
print("③ 打印xList地址:", id(xList))
print("③ 打印y地址:", id(y))
控制台输出:
▼ 测试copy操作 ▼
① 执行函数前:
① 打印xList值: [1, 2, 3, 4]
① 打印y值: 0
① 打印xList地址: 2207082895176
① 打印y地址: 140712246210784
② testFunc2打印xList地址: 2207082895176
② testFunc2打印y地址: 140712246210784
② testFunc2打印xListCopy地址: 2207082895048
② testFunc2打印yCopy地址: 140712246210816
② testFunc2打印xListCopy值: [1, 2, 3, 4, 5]
③ 执行函数后:
③ 打印xList值: [1, 2, 3, 4]
③ 打印y值: 0
③ 打印xList地址: 2207082895176
③ 打印y地址: 140712246210784
xListCopy是xList复制的对象,位于另一个内存地址;所以xList和xListCopy内存地址不一样;
由于xListCopy是xList复制的对象,所以对xListCopy列表增加一个元素,不会影响到xList的值。