声明一个学生类类型,实现对一名学生信息的输入和输出 和 实现对20名学生信息的输入和输出
时间: 2023-05-30 11:04:26 浏览: 69
表示并输出一个学生信息JAVA
以下是Python语言的实现:
```python
class Student:
def __init__(self, name, age, gender, grade):
self.name = name
self.age = age
self.gender = gender
self.grade = grade
def __str__(self):
return f"Name: {self.name}, Age: {self.age}, Gender: {self.gender}, Grade: {self.grade}"
@staticmethod
def input_student_info():
name = input("Name: ")
age = int(input("Age: "))
gender = input("Gender: ")
grade = int(input("Grade: "))
return Student(name, age, gender, grade)
@staticmethod
def input_students_info(num):
students = []
for i in range(num):
print(f"Input information of student {i+1}:")
student = Student.input_student_info()
students.append(student)
return students
@staticmethod
def output_students_info(students):
for i, student in enumerate(students):
print(f"Information of student {i+1}:")
print(student)
```
上述代码中,我们声明了一个名为`Student`的学生类,包括姓名、年龄、性别和年级四个属性。`__str__`方法用于将学生的信息以字符串形式输出。`input_student_info`方法用于输入单个学生的信息,`input_students_info`方法用于输入多个学生的信息,`output_students_info`方法用于输出多个学生的信息。
我们可以使用以下代码来测试上述类的功能:
```python
# 输入单个学生信息并输出
student = Student.input_student_info()
print(student)
# 输入多个学生信息并输出
students = Student.input_students_info(20)
Student.output_students_info(students)
```
运行输出:
```
Name: Alice
Age: 18
Gender: Female
Grade: 3
Name: Alice, Age: 18, Gender: Female, Grade: 3
Input information of student 1:
Name: Alice
Age: 18
Gender: Female
Grade: 3
Input information of student 2:
Name: Bob
Age: 17
Gender: Male
Grade: 2
...
Input information of student 20:
Name: Zoe
Age: 16
Gender: Female
Grade: 1
Information of student 1:
Name: Alice, Age: 18, Gender: Female, Grade: 3
Information of student 2:
Name: Bob, Age: 17, Gender: Male, Grade: 2
...
Information of student 20:
Name: Zoe, Age: 16, Gender: Female, Grade: 1
```
阅读全文