我在寻找比较两个类实例的内容的最有效的方式的最有效方式。我有一个包含这些类实例的列表,并且在追加到列表之前,我想确定它们的属性值是否相同。这对大多数人来说可能看起来微不足道,但在仔细阅读这些论坛之后,我并没有明确自己想要做什么。另请注意,我没有编程背景。在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))
然后加入到我的清单,我会做一些事情,如:
found = False
for instance in myList:
if instance._compare(newInstance):
found = True
Break
if not found: myList.append(newInstance)
但我不清楚这是否是最有效的或者比较同一类的实例内容的python-ic方法。
你应该把它们放在一个集合中,并在你的类中实现'__hash__'和'__eq__'。 – khachik