引述
print([1, 2] == [1, 2])
print(2 > 5)
print("a" <= "b")
输出结果为:
True
False
True
在python中我们经常会比较两个数据结构是否相等,或者比较两个数据结构的大小叫做rich comparison。
rich comparison一共包含了六个操作符。
在python的内置数据结构中,比如说dict,或者list,尤其是integer、string、float,它们的rich comparison都是有良好的定义的。
然而,有时候对于我们自己写的数据结构,我们也希望利用这些比较运算符。
而比较的逻辑实现,我们就是通过魔术方法来完成的。
我们举个例子:
class Date:
def __init__(self, year, month, date):
self.year = year
self.month = month
self.date = date
x = Date(2022, 2, 22)
y = Date(2022, 2, 22)
print(x == y)
输出结果为:
False
在python中,当你没有去写一个类的比较逻辑的时候,它默认比较两个对象的是否相等的方法是会默认调用object.__eq__
方法,默认比较两个对象的地址(id),默认调用了is
。
python中常见的比较魔术方法
__eq__
魔术方法
__eq__
是 Python 中一个重要的魔术方法,它用于判断两个对象是否相等。
__eq__
方法默认情况下是比较两个对象的内存地址是否相等,即 id(self) == id(other)
。如果我们想让自定义的类支持比较操作,就需要自定义 __eq__
方法。
class Date:
def __init__(self, year, month, date):
self.year = year
self.month = month
self.date = date
def __eq__(self, other):
print("__eq__")
return self.year == other.year and self.month == other.month and self.date == other.date
x = Date(2022, 2, 22)
y = Date(2022, 2, 22)
print(x == y)
print(x != y)
输出结果为:
__eq__
True
__eq__
False
这里我们并没有定义不等于,python默认调用了__eq__
后取反。
__ne__
魔术方法
__ne__
是Python的一个魔术方法,用于比较两个对象是否不相等。它是“not equal”的缩写,与__eq__
(等于)方法相对应。当使用!=
操作符时,解释器就会调用__ne__
方法来执行不相等的比较。
__ne__
方法的默认实现是返回not self == other
。因此,如果你在类中定义了__eq__
方法,那么你应该同时定义__ne__
方法,以确保比较的正确性。
class Date:
def __init__(self, year, month, date):
self.year = year
self.month = month
self.date = date
def __eq__(self, other):
print