我们可以使用 Python 中的内置比较函数 cmp() 来比较两个对象的属性。但是,如果比较结果是相等的,则返回 0,如果属性不相等,则返回非零值。为了避免误解,我们应该显式地检查比较结果和值是否相等。
示例代码:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __cmp__(self, other):
if self.name < other.name:
return -1
elif self.name > other.name:
return 1
else:
return cmp(self.age, other.age)
person1 = Person("Eric", 30)
person2 = Person("John", 25)
if person1.__cmp__(person2) == 0:
print("The names and ages are equal.")
else:
print("The names and ages are not equal.")
这个例子中,我们定义了一个 Person 类,它有两个属性:姓名和年龄。然后,我们定义了一个 cmp() 函数来比较两个 Person 实例的属性。如果两个实例的姓名不同,则按字母顺序排序。如果姓名相同,则按年龄排序。最后,我们检查比较结果是否为 0,如果是,则表示属性相等;否则,表示属性不相等。