Python 中的 __eq__ 方法

Haider Ali 2022年5月17日
Python 中的 __eq__ 方法

本指南将展示我们如何在 Python 中处理 __eq__() 方法。我们将组合不同的对象并学习这种特定方法的功能。让我们深入了解它。

Python 中的 __eq__()

首先,__eq__() 是一个 dunder/magic 方法,如你所见,它前面和后面都有双下划线。每当你使用 == 运算符时,都会调用此方法来比较两个类实例。如果你没有为 __eq__() 方法提供特定实现,Python 将使用 is 运算符进行比较。但是你如何指定这个方法呢?答案在于覆盖这个函数。看看下面的代码。

#__eq__ this is called dunder/magic method in python

#class of student has constructor with two arguments
class Student:
    def __init__(self,name,roll):
        self.name=name
        self.roll=roll


#object one of class student
s1=Student("David",293)
#object two of class student
s2=Student("David",293)


#Applying equality function two objects 
print(s1 == s2)

输出:

False

如你所见,我们创建了一个名为 Student 的类,并将其两个参数设置为 nameroll。后来,你创建了两个具有相同 Student 类数据的实例。正如我们在上面的代码中所做的那样比较这两个实例将给出一个 false 输出。

尽管这些实例具有相同的数据,但它们在比较后并不相等。这是因为 == 运算符比较了 case 的地址,这是不同的。你可以通过运行以下代码和上面的代码来看到这一点。

#Both objects have different ids thats why the s1==s2 is false
print(id(s1))
print(id(s2))

输出:

1991016021344   //(it will vary)
1991021345808   //(it will vary)

但是,如果我们要创建一个实例,然后在另一个示例中保存该实例,如下所示,它们的地址将是相同的。看一看。

#object one of class student
s1=Student("Ahsan",293)
s3=s1

#In this case we have same id for s1 and s3
print(s1 == s3)
print(id(s1))
print(id(s3))

输出:

True
1913894976432  //(it will vary)
1913894976432  //(it will vary)

它会给你 true 作为输出。那么,我们如何根据数据比较两个实例呢?我们需要实现 dunder 方法并像下面这样覆盖它。

#class of student has constructor with two arguments and a modified dunder method of __eq__
class Student:
    def __init__(self,name,roll):
        self.name=name
        self.roll=roll
    #implementing the dunder method
    def __eq__(self,obj):
        #checking both objects of same class
        if isinstance(obj,Student):
            if self.roll == obj.roll:
                return True
            else:
                return False


#object of class student
s4=Student("David",293)
#other object of class student
s5=Student("David",293)

#Applying equality function two objects
print(s4==s5)


#Both objects have different ids, but the s4==s5 is true because we override the __eq__ function it will give true when the roll number is some
print(id(s4))
print(id(s5))


#object of class student
s6=Student("David",293)
#other object of class student
s7=Student("David",178)


#Applying equality function two objects will give us False because the roll is different
print(s6==s7)

输出:

True
1935568125136   //(it will vary)
1935568124656   //(it will vary)
False

现在,我们通过在里面放置一个检查 roll 是否相同的 if 条件来覆盖 __eq__() 方法。这就是你在 Python 中覆盖 __eq__() 方法的方式。

Author: Haider Ali
Haider Ali avatar Haider Ali avatar

Haider specializes in technical writing. He has a solid background in computer science that allows him to create engaging, original, and compelling technical tutorials. In his free time, he enjoys adding new skills to his repertoire and watching Netflix.

LinkedIn