我在尋找比較兩個類實例的內容的最有效的方式的最有效方式。我有一個包含這些類實例的列表,並且在追加到列表之前,我想確定它們的屬性值是否相同。這對大多數人來說可能看起來微不足道,但在仔細閱讀這些論壇之後,我並沒有明確自己想要做什麼。另請注意,我沒有編程背景。在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