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.')