覆盖 Pythons __eq__ 方法,isistance 和 eq mothods 返回 false



我是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"

程序返回:不等于。

您的第一个问题是isinstance(self, other)不是问selfother是否都是兼容类型的实例,或者它们是否是同一个实例(正如您的评论所说),而是问self是否是other类型的实例。由于other甚至不是一个类型,所以答案总是错误的。

你可能想要isinstance(self, type(other))。或者更复杂的东西,比如isinstance(self, type(other)) or isinstance(other, type(self))

或者也许你根本就不想这样;即使对于相等性测试,鸭子类型通常也是个好主意。如果other具有与self相同的属性,并且哈希为相同的值,这足够好吗?答案可能是否定的……但你绝对应该问这个问题。


您的第二个问题是对is:的误解

if (instance1 is instance2):
    print "equals"
else:
    print "not equals"

is的全部意义在于,它询问的是这两个是否是同一对象,而不是这两个(可能不同的)对象是否彼此相等。例如:

>>> a = []
>>> b = []
>>> a == b
True
>>> a is b
False

它们都是空列表,所以它们彼此相等,但它们是两个不同的空列表,这就是为什么你可以这样做:

>>> a.append(0)
>>> b
[]

你们班也是如此。您创建的每个Instance都将是一个不同的、独立的实例——即使它们都是相等的。

您定义的__eq__方法自定义了==运算符。无法自定义is运算符。

最新更新