不使用copy模块实现字典深拷贝时出现str无copy属性错误的原因是什么?
错误触发原因
- 你代码中默认字典的所有value都支持
copy()方法,但Python的字符串(str)属于不可变基本数据类型,本身没有实现copy()实例方法,当遍历到值为字符串的键值对时,调用values.copy()就会抛出对应AttributeError。 - 额外补充:你当前的实现逻辑本身也不符合深拷贝的要求,仅能处理value为单层可变容器(如列表、字典)的场景,如果存在嵌套的可变结构,拷贝后的对象依然会和原对象共用内部嵌套的引用,无法达到深拷贝效果。
无copy模块的修正实现参考
如果要在不导入copy模块的前提下实现基础的字典深拷贝,可以按值的类型做分支处理,不可变类型直接赋值即可,可变容器类型递归处理:
def deepcopy(data: dict): copy_dict = {} for key, value in data.items(): if isinstance(value, dict): # 嵌套字典递归拷贝 copy_dict[key] = deepcopy(value) elif isinstance(value, list): # 列表元素递归处理 copy_dict[key] = [deepcopy(item) if isinstance(item, (dict, list)) else item for item in value] else: # 字符串、数值、布尔等不可变类型直接赋值,无需额外拷贝 copy_dict[key] = value return copy_dict # 测试代码 old = {"Lion": "brave", "Tiger": "striped", "ext": {"age": 3, "tags": ["carnivore", "wild"]}} copied_dict = deepcopy(old) copied_dict["ext"]["age"] = 4 print(old) # 原字典不受修改影响:{'Lion': 'brave', 'Tiger': 'striped', 'ext': {'age': 3, 'tags': ['carnivore', 'wild']}} print(copied_dict) # 拷贝后的字典修改成功:{'Lion': 'brave', 'Tiger': 'striped', 'ext': {'age': 4, 'tags': ['carnivore', 'wild']}}
内容的提问来源于stack exchange,提问作者Sruthi Gopalakrishnan
相关产品推荐
相关产品推荐

