请用python 写2个类,一个是person类,包括姓名,性别,年龄,婚否。另一个是关系类,包括3个方法,2个人结婚并能查出对象是谁,2个人离婚并能显示没有对象了。生成2个person对象,让他们2个结婚,并分别显示对象是谁,再让他们2个离婚,并分别显示都没有对象了。
时间: 2023-05-20 17:06:39 浏览: 112
好的,以下是代码:
```python
class Person:
def __init__(self, name, gender, age, married):
self.name = name
self.gender = gender
self.age = age
self.married = married
class Relationship:
def __init__(self, person1, person2):
self.person1 = person1
self.person2 = person2
def get_partner(self, person):
if person == self.person1:
return self.person2.name
elif person == self.person2:
return self.person1.name
else:
return "This person is not in the relationship."
def divorce(self):
self.person1.married = False
self.person2.married = False
self.person1 = None
self.person2 = None
# 创建两个 Person 对象
person1 = Person("张三", "男", 30, False)
person2 = Person("李四", "女", 28, False)
# 让他们结婚
relationship = Relationship(person1, person2)
person1.married = True
person2.married = True
# 显示对象是谁
print(person1.name + " 的对象是 " + relationship.get_partner(person1))
print(person2.name + " 的对象是 " + relationship.get_partner(person2))
# 让他们离婚
relationship.divorce()
# 显示都没有对象了
print(person1.name + " 没有对象了。")
print(person2.name + " 没有对象了。")
```
输出结果:
```
张三 的对象是 李四
李四 的对象是 张三
张三 没有对象了。
李四 没有对象了。
```
阅读全文