实现copy.deepcopy()克隆函数

时间:2017-11-01 04:42:09

标签: python deep-copy

仅用于教育目的,我尝试实施copy.deepcopy()的克隆功能。

玩完代码和Google搜索后,我想出了以下功能:

def my_deepcopy(data):

    if isinstance(data, dict):
        result = {}
        for key, value in data.items():
            result[key] = my_deepcopy(value)

        assert id(result) != id(data)

    elif isinstance(data, list):
        result = []
        for item in data:
            result.append(my_deepcopy(item))

        assert id(result) != id(data)

    elif isinstance(data, tuple):
        aux = []
        for item in data:
            aux.append(my_deepcopy(item))
        result = tuple(aux)

        assert id(result) != id(data)

    elif isinstance(data, (int, float, type(None), str, bool)):
        result = data
    else:
        raise ValueError("unexpected type")

    return result

似乎使用所有Python基元类型及其组合:

# Various object types
lst_obj = [ 0, 1.1, 'foo', 'bar' ]
dict_obj = { 'zero' : 0, 'pi' : 3.1415, 'desc' : 'foobar' }
list_list_obj = [ [1,2,3], [4,5,6], [7,8,9] ]
tuple_list_obj = [ (-1,-1), (0,-1,0), (-1,0), (0,0,0,0) ]
dict_list_obj = [ {'zero' : 0}, {'pi' : 3.1415}, {'desc' : 'foobar'} ]

# Testing
my_deepcopy( lst_obj )        #OK!
my_deepcopy( dict_obj )       #OK!
my_deepcopy( list_list_obj )  #OK!
my_deepcopy( tuple_list_obj ) #OK!
my_deepcopy( dict_list_obj )  #OK!

到目前为止,这很好,但是Arbitrary Types呢?如何复制任意对象的实例?我该如何检测到它?任意类型都有任何类型的复制构造函数吗?

我的函数中缺少以下代码的功能:

class Xpto:
    pass

arbitrary = [ Xpto(), Xpto() ]
my_deepcopy( arbitrary )     #ValueError("unexpected type")

1 个答案:

答案 0 :(得分:1)

你可以做一些"类别检查"为了更好地设计您的函数,通过任意对象的VSCode 1.17.2属性搜索序列或映射:

__dict__

同时检查>>> import collections >>> isinstance([], collections.Sequence) True >>> isinstance((), collections.Sequence) True >>> isinstance('foo', collections.Sequence) True >>> isinstance({}, collections.Mapping) True >>> isinstance(23, collections.Sequence) False >>> isinstance(None, collections.Sequence) False __class__属性,检查对象是否是从if语句中没有的某个类类型中实例化的,例如:

__name__
相关问题