可以使用Python内置的functools库中的total_ordering装饰器和__eq__魔术方法实现比较不同类的对象实例是否相等,基于其属性。
示例代码如下:
from functools import total_ordering
@total_ordering class Animal: def init(self, name, age): self.name = name self.age = age
def __eq__(self, other):
if isinstance(other, Animal):
return self.name == other.name and self.age == other.age
return NotImplemented
@total_ordering class Person: def init(self, name, age): self.name = name self.age = age
def __eq__(self, other):
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return NotImplemented
animal1 = Animal("dog", 5) animal2 = Animal("dog", 5) person1 = Person("John", 30) person2 = Person("John", 30)
print(animal1 == animal2) # True print(person1 == person2) # True print(animal1 == person1) # False