8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

比较 Python 对象与 deepcopy

purushottam kumar 2月前

15 0

有没有办法将 Python 对象与深度复制生成的对象进行比较?例如: import copy original_object = SomeObject() cloned_object = copy.deepcopy(original_object)

有没有办法将 Python 对象与深度复制生成的对象进行比较?

例如:

    import copy 

    original_object = SomeObject()
    cloned_object = copy.deepcopy(original_object)
    assertDeepCopy(original_object, cloned_object)
帖子版权声明 1、本帖标题:比较 Python 对象与 deepcopy
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由purushottam kumar在本站《object》版块原创发布, 转载请注明出处!
最新回复 (0)
  • 您的问题不清楚。您说的比较是什么意思?这两个对象是不同的,但如果 deepcopy() 成功,它们就是“相同的”(相同的方法、相同的基类、相同的属性等)。

  • 此解决方案允许您深度比较对象、字典、列表和基元。并且允许您从比较中排除键。

    我认为这可能对那些寻求深度比较对象支持的人有帮助:)

    def deep_compare(left, right, excluded_keys = []):
        # convert left and right to dicts if possible, skip if they can't be converted
        try: 
            left = left.__dict__
            right = right.__dict__
        except:
            pass
    
        # both sides must be of the same type 
        if type(left) != type(right):
            return False
    
        # compare the two objects or dicts key by key
        if type(left) == dict:
            for key in left:
                # make sure that we did not exclude this key
                if key not in excluded_keys:
                    # check if the key is present in the right dict, if not, we are not equals
                    if key not in right:
                        return False
                    else:
                        # compare the values if the key is present in both sides
                        if not deep_compare(left[key], right[key], excluded_keys):
                            return False
    
            # check if any keys are present in right, but not in left
            for key in right:
                if key not in left and key not in excluded_keys:
                    return False
            
            return True
    
        # check for each item in lists
        if type(left) == list:
            # right and left must have the same length
            if len(left) != len(right):
                return False
    
            # compare each item in the list
            for index in range(len(left)):
                if not deep_compare(left[index], right[index], excluded_keys):
                    return False
    
        # do a standard comparison
        return left == right
    
  • 我相信您要的是:

    def deep_compare(left, right):
        try:
            if not left.__dict__:
                return left == right
    
            for key in left.__dict__:
                if key not in right.__dict__:
                    return false
                else:
                    return deep_compare(left[key], right[key])
        except (AttributeError, TypeError):
            return left == right 
    

    但是,请注意,这可能会在很多地方出错:如果对象没有 == 以您喜欢的方式定义,您将无法得到想要的答案。

  • 我知道这是一个老答案,但是对于 Python 3,以前的代码对我来说不起作用,因此我在这个对我来说更好的代码中进行了更新:

    
    import logging
    log = logging.getLogger(__name__)
    
    ...
    
        def deep_compare(self,left, right, level=0):
            if type(left) != type(right):
                log.info("Exit 1 - Different types")
                return False
    
            elif type(left) is dict:
                # Dict comparison
                for key in left:
                    if key not in right:
                        log.info("Exit 2 - missing {} in right".format(key))
                        return False
                    else:
                        if not deep_compare(left[str(key)], right[str(key)], level +1 ):
                            log.info("Exit 3 - different children")
                            return False
                return True
            elif type(left) is list:
                # List comparison
                for key in left:
                    if key not in right:
                        log.info("Exit 4 - missing {} in right".format(key))
                        return False
                    else:
                        if not deep_compare(left[left.index(key)], right[right.index(key)], level +1 ):
                            log.info("Exit 5 - different children")
                            return False
                return True
            else:
                # Other comparison
                return left == right
    
            return False
    
    

    它比较字典、列表和任何其他自行实现 \'==\' 运算符的类型。如果需要比较其他不同的东西,则需要在 \'if tree\' 中添加一个新分支。

    希望有所帮助。

返回
作者最近主题: