【一个例子让你明白python的赋值和拷贝】

# 1.赋值操作
def print_fuzhi():
    """
    赋值操作中时间里一份数据的引用,如果数据发生变化,所有的引用都发生变化
    """
    a = {
        "name": "alex",
        "age": 18,
        "gender": False,
        "hobby": [1, 2, 3],
        "other": {
            "address": "chaoyangqu",
        }
    }
    print("-" * 10 + "赋值操作" + "-" * 10)
    b = a
    print(f"元数据的地址:{id(a), id(b)}")
    print(f"深层对象的地址:{id(a['hobby']), id(b['hobby'])}")
    b["name"] = "bob"
    b["hobby"][0] = 10
    b["hobby"].append(4)
    b["other"]["school"] = "北大"
    print(f"a:{a}")
    print(f"b:{b}")


# 2.浅copy
def print_copy():
    """
    浅拷贝拷贝地址
    浅拷贝对于只拷贝对象数据的第一层,其他层仍然是引用
    """
    a = {
        "name": "alex",
        "age": 18,
        "gender": False,
        "hobby": [1, 2, 3],
        "other": {
            "address": "chaoyangqu",
        }
    }
    print("-" * 10 + "浅拷贝" + "-" * 10)
    from copy import copy
    b = copy(a)
    print(f"元数据的地址:{id(a), id(b)}")
    print(f"深层对象的地址:{id(a['hobby']), id(b['hobby'])}")
    b["name"] = "bob"
    b["hobby"][0] = 10
    b["hobby"].append(4)
    b["other"]["school"] = "北大"
    print(f"a:{a}")
    print(f"b:{b}")


# 3.深拷贝
def print_deepcopy():
    """
    深拷贝拷贝的是数据
    深拷贝对于只拷贝对象数据的所有层,数据完全隔离
    """
    a = {
        "name": "alex",
        "age": 18,
        "gender": False,
        "hobby": [1, 2, 3],
        "other": {
            "address": "chaoyangqu",
        }
    }
    print("-" * 10 + "深拷贝" + "-" * 10)
    from copy import deepcopy
    b = deepcopy(a)
    print(f"元数据的地址:{id(a), id(b)}")
    print(f"深层对象的地址:{id(a['hobby']), id(b['hobby'])}")
    b["name"] = "bob"
    b["hobby"][0] = 10
    b["hobby"].append(4)
    b["other"]["school"] = "北大"
    print(f"a:{a}")
    print(f"b:{b}")


print_fuzhi()
print_copy()
print_deepcopy()
"""
>>>
----------赋值操作----------
元数据的地址:(140624057016560, 140624057016560)
深层对象的地址:(140624056103392, 140624056103392)
a:{'name': 'bob', 'age': 18, 'gender': False, 'hobby': [10, 2, 3, 4], 'other': {'address': 'chaoyangqu', 'school': '北大'}}
b:{'name': 'bob', 'age': 18, 'gender': False, 'hobby': [10, 2, 3, 4], 'other': {'address': 'chaoyangqu', 'school': '北大'}}
----------浅拷贝----------
元数据的地址:(140624056999200, 140624056999840) # 原对象的地址不一样说明是拷贝的数据
深层对象的地址:(140624056103392, 140624056103392) # 深层对象的地址一样说明是拷贝的地址
a:{'name': 'alex', 'age': 18, 'gender': False, 'hobby': [10, 2, 3, 4], 'other': {'address': 'chaoyangqu', 'school': '北大'}}
b:{'name': 'bob', 'age': 18, 'gender': False, 'hobby': [10, 2, 3, 4], 'other': {'address': 'chaoyangqu', 'school': '北大'}}
----------深拷贝----------
元数据的地址:(140624057016560, 140624056999440)
深层对象的地址:(140624056103392, 140624057377088)
a:{'name': 'alex', 'age': 18, 'gender': False, 'hobby': [1, 2, 3], 'other': {'address': 'chaoyangqu'}}
b:{'name': 'bob', 'age': 18, 'gender': False, 'hobby': [10, 2, 3, 4], 'other': {'address': 'chaoyangqu', 'school': '北大'}}
"""
posted @ 2021-10-28 16:32  GokuBlog  阅读(51)  评论(0编辑  收藏  举报