Python: 浅拷贝(shallow copy) 深拷贝(deep copy)Python: 浅拷贝(shallow copy) 深拷贝(deep copy)Python: 浅拷贝(shallow copy) 深拷贝(deep copy)Python: 浅拷贝(shallow copy) 深拷贝(deep copy)
  • 首页
  • 博客
  • 文件
  • 书签
  • 分析
  • 登录
Search
Generic filters

Python: 浅拷贝(shallow copy) 深拷贝(deep copy)

Published by admin at 2022年4月30日
Categories
  • Python
Tags
import copy
from filecmp import cmp


class MyClass:
    def __init__(self, name):
        self.name = name

    def __cmp__(self, other):
        return cmp(self.name, other.name)


a = MyClass('a')
myList = [a]
shallow_copy = myList.copy()
print('myList: ', myList)
print('shallow_copy: ', shallow_copy)
print('shallow_copy is myList: ', (shallow_copy is myList))
print('shallow_copy == myList: ', (shallow_copy == myList))
print('shallow_copy[0] is myList[0]: ', (shallow_copy[0] is myList[0]))
print('shallow_copy[0] == myList[0]', (shallow_copy[0] == myList[0]))

print("*"*20)

deep_copy = copy.deepcopy(myList)
print('myList: ', myList)
print('deep_copy: ', deep_copy)
print('deep_copy is myList: ', (deep_copy is myList))
print('deep_copy == myList: ', (deep_copy == myList))
print('deep_copy[0] is myList[0]: ', (deep_copy[0] is myList[0]))
print('deep_copy[0] == myList[0]', (deep_copy[0] == myList[0]))

运行结果:
myList: [<__main__.MyClass object at 0x0000000002617EB0>]
shallow_copy: [<__main__.MyClass object at 0x0000000002617EB0>]
shallow_copy is myList: False
shallow_copy == myList: True
shallow_copy[0] is myList[0]: True
shallow_copy[0] == myList[0] True
********************
myList: [<__main__.MyClass object at 0x0000000002617EB0>]
deep_copy: [<__main__.MyClass object at 0x00000000026BB430>]
deep_copy is myList: False
deep_copy == myList: False
deep_copy[0] is myList[0]: False
deep_copy[0] == myList[0] False

发表回复 取消回复

您的电子邮箱地址不会被公开。 必填项已用*标注

Categories

  • 猫
  • Python
  • MySQL
  • Django
  • Html/CSS
  • JavaScript
  • Vue
  • RegExp
  • php
  • Practice
  • Virtualization
  • Linux
  • Windows
  • Android
  • NAS
  • Software
  • Hardware
  • Network
  • Router
  • Office
  • WordPress
  • SEO
  • English
  • Games
  • Recipes
  • living
  • Memorandum
  • Essays
  • 未分类

归档

©2015-2022 Alaica Blog support@alaica.com