支持Student对象和Worker对象判断对象是否相等的运算,即==运算符,ID相等即认为是相等。
时间: 2024-05-01 22:19:06 浏览: 165
好的,我可以为你提供一个示例代码,来实现支持Student对象和Worker对象判断对象是否相等的运算:
```python
class Student:
def __init__(self, name, student_id):
self.name = name
self.student_id = student_id
def __eq__(self, other):
if isinstance(other, Student):
return self.student_id == other.student_id
return False
class Worker:
def __init__(self, name, worker_id):
self.name = name
self.worker_id = worker_id
def __eq__(self, other):
if isinstance(other, Worker):
return self.worker_id == other.worker_id
return False
student1 = Student("John", 123)
student2 = Student("Lisa", 456)
worker1 = Worker("Bob", 789)
worker2 = Worker("Alice", 456)
print(student1 == student2) # False
print(student1 == worker1) # False
print(student2 == worker2) # False
print(student1 == Student("John", 123)) # True
print(worker1 == Worker("Bob", 789)) # True
```
在上面的代码中,我们为`Student`和`Worker`类分别定义了`__eq__`方法,用于判断两个对象是否相等,其中,如果传入的参数是同一类型的对象,并且ID相等,我们就认为这两个对象相等。然后我们创建了四个对象,分别是`student1`、`student2`、`worker1`和`worker2`,并分别测试了它们之间的相等性。
阅读全文