__eq__方法的功能的demo
时间: 2023-12-17 18:04:06 浏览: 38
Sure, here's a demo of the functionality of the "__eq__" method:
```
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 False
p1 = Person("John", 36)
p2 = Person("John", 36)
p3 = Person("Alice", 24)
print(p1 == p2) # True
print(p1 == p3) # False
```
In this example, we define a class "Person" with a "__eq__" method. This method allows us to compare two instances of the class to determine if they are equal. In this case, we compare two instances based on their name and age. If both values match, we return True, otherwise we return False.
We create three instances of the "Person" class and compare them using the "__eq__" method. The first comparison between p1 and p2 returns True because they have the same name and age. The second comparison between p1 and p3 returns False because they have different names.