小编Kla*_*kus的帖子

比较python中两个类实例的内容的最有效方法

我正在寻找比较两个类实例的内容的最有效方法.我有一个包含这些类实例的列表,在附加到列表之前,我想确定它们的属性值是否相同.这对大多数人来说似乎微不足道,但在仔细阅读这些论坛后,我无法具体到我想要做的事情.另请注意,我没有编程背景.

这是我到目前为止:

class BaseObject(object):
    def __init__(self, name=''):
        self._name = name


    def __repr__(self):
        return '<{0}: \'{1}\'>'.format(self.__class__.__name__, self.name)

    def _compare(self, other, *attributes):
        count = 0
        if isinstance(other, self.__class__):
            if len(attributes):
                for attrib in attributes:
                    if (attrib in self.__dict__.keys()) and (attrib in other.__dict__.keys()):
                        if self.__dict__[attrib] == other.__dict__[attrib]:
                            count += 1
                return (count == len(attributes))
            else:
                for attrib in self.__dict__.keys():
                    if (attrib in self.__dict__.keys()) and (attrib in other.__dict__.keys()):
                        if self.__dict__[attrib] == other.__dict__[attrib]:
                            count += 1
                return (count == len(self.__dict__.keys()))
    def _copy(self):
        return (copy.deepcopy(self))
Run Code Online (Sandbox Code Playgroud)

在添加到我的列表之前,我会执行以下操作: …

python object instance

1
推荐指数
2
解决办法
3729
查看次数

标签 统计

instance ×1

object ×1

python ×1