Python 的对象天生拥有一些神奇的方法,它们总被双下划线所包围,它们是面向对象的 Python 的一切。它们是可以给你的类增加魔力的特殊方法,如果你的对象实现(重载)了某一个魔法方法,那么这个方法就会在特殊的情况下自动被 Python 所调用。
功能
定义等于号的行为:x == y, 相当于 x.__eq __(y)。
参数
self 表示小于号左边的对象,other 表示小于号右边的对象。
返回值
一般返回 False 或 True。
示例
class MyTest(object):
def __init__(self, age):
self.age = age
def __eq__(self, other):
print(f'eq use exp.')
return self.age == other.age
my_age = MyTest(21)
other_age = MyTest(21)
if my_age == other_age:
print('my age eq to other age.')