Skip to main content
 首页 » 编程设计

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

2025年05月04日13tuyile006

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

这是我目前所拥有的:

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)) 

在添加到我的列表之前,我会做类似的事情:

found = False 
for instance in myList: 
    if instance._compare(newInstance):  
        found = True 
        Break 
 
if not found: myList.append(newInstance) 

但是我不清楚这是否是比较同一类实例内容的最有效或 python-ic 方式。

请您参考如下方法:

实现 __eq__ special method相反:

def __eq__(self, other, *attributes): 
    if not isinstance(other, type(self)): 
        return NotImplemented 
 
    if attributes: 
        d = float('NaN')  # default that won't compare equal, even with itself 
        return all(self.__dict__.get(a, d) == other.__dict__.get(a, d) for a in attributes) 
 
    return self.__dict__ == other.__dict__ 

现在你可以使用:

if newInstance in myList: 

Python 会自动使用 __eq__ 特殊方法来测试是否相等。

在我的版本中,我保留了传递一组有限属性的能力:

instance1.__eq__(instance2, 'attribute1', 'attribute2') 

但是使用 all() 来确保我们只测试需要的部分。

请注意,我们返回了 NotImplemented,这是一个特殊的单例对象,表示不支持比较; Python 将询问 other 对象是否支持相等性测试而不是这种情况。