我是来自 Java 世界的 Python 新手。
我编写了一个名为“Instance”的 Python 类,它具有 3 个属性(属性、值和类)。我想覆盖“ eq ”方法和“ hash ”方法,我正在使用用于对象比较的“attribute”和“value”属性。我用相同的值实例化了两个对象,但是它们返回不相等。
代码如下,类实例:
'''Class of type Instance'''
class Instance(object):
__attribute = None;
__value = None;
__classification = None;
#constructor
def __init__(self,attribute,value,classification):
self.attribute = attribute;
self.value = value;
self.classification = classification;
#setters & getters
def setAttribute(self,attribute):
self.attribute = attribute
def setValue(self,value):
self.value = value
def setClassification(self,classification):
self.classification = classification
def getAttribute(self):
return self.Attribute;
def getValue(self):
return self.Value
def getClassification(self):
return self.Classification
def __eq__(self, other):
#if self & other are the same instance & attribute & value equal
return isinstance(self,other) and (self.attribute == other.attribute) and (self.value == other.value)
def __hash__(self):
return hash(self.attribute, self.value)
我正在实例化另一个名为 Testing 的 Python 模块:
if __name__ == '__main__':
pass
from Instance import *
instance1 = Instance('sameValue', 1,'Iris-setosa')
instance2 = Instance('sameValue', 1,'Iris-setosa')
if (instance1 is instance2):
print "equals"
else:
print "not equals"
程序返回:不等于。