在 Python 中,__eq__
是用于实现“等于”(==
)比较运算符的特殊方法。通过定义 __eq__
方法,你可以自定义对象的相等性逻辑,使得两个对象可以通过 ==
运算符进行比较
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def __eq__(self, other):
# 检查 other 是否是 Student 类型
if isinstance(other, Student):
# 判断 name 和 age 是否都相等
return self.name == other.name and self.age == other.age
return False # 如果 other 不是 Student 类型,返回 False
# 创建两个 Student 对象
stu1 = Student("小明", 18)
stu2 = Student("小明", 18)
stu3 = Student("小红", 20)
# 使用 == 比较
print(stu1 == stu2) # 输出: True
print(stu1 == stu3) # 输出: False