创建两个学生对象s1和s2并初始化,两个对象的属性分别为自己和与自己学号相近的同学信息,然后分别显示这两个学生的信息,并将自己的年龄修改为增大5岁,再显示修改后同学的信息。
时间: 2023-06-19 20:10:50 浏览: 35
以下是 Python 代码实现:
```python
class Student:
def __init__(self, name, age, student_id):
self.name = name
self.age = age
self.student_id = student_id
def display_info(self):
print("Name:", self.name)
print("Age:", self.age)
print("Student ID:", self.student_id)
print()
def increase_age(self, years):
self.age += years
# 创建两个学生对象s1和s2并初始化,两个对象的属性分别为自己和与自己学号相近的同学信息
s1 = Student("Tom", 18, "20210001")
s2 = Student("Jerry", 20, "20210002")
# 分别显示这两个学生的信息
print("Information of student 1:")
s1.display_info()
print("Information of student 2:")
s2.display_info()
# 将自己的年龄修改为增大5岁
s1.increase_age(5)
# 再显示修改后同学的信息
print("Information of student 1 after increasing age by 5 years:")
s1.display_info()
print("Information of student 2:")
s2.display_info()
```
输出结果为:
```
Information of student 1:
Name: Tom
Age: 18
Student ID: 20210001
Information of student 2:
Name: Jerry
Age: 20
Student ID: 20210002
Information of student 1 after increasing age by 5 years:
Name: Tom
Age: 23
Student ID: 20210001
Information of student 2:
Name: Jerry
Age: 20
Student ID: 20210002
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)