请给我一个Python面向对象程序设计的案例
时间: 2024-02-09 08:13:39 浏览: 81
好的,下面是一个简单的Python面向对象程序设计的案例:
假设我们要设计一个学生管理系统,其中有两个类:Student 和Class。
```
class Student:
def __init__(self, name, age, gender, id):
self.name = name
self.age = age
self.gender = gender
self.id = id
def display(self):
print("Name:", self.name)
print("Age:", self.age)
print("Gender:", self.gender)
print("ID:", self.id)
class Class:
def __init__(self, name, students):
self.name = name
self.students = students
def add_student(self, student):
self.students.append(student)
def remove_student(self, student):
self.students.remove(student)
def display(self):
print("Class Name:", self.name)
print("Students:")
for student in self.students:
student.display()
print("--------------------")
```
以上代码中,Student 类表示一个学生,包含了学生的姓名、年龄、性别和学号等信息,并且有一个 display() 方法用于显示学生信息。
Class 类表示一个班级,包含了班级的名称和学生列表,并且有 add_student() 和 remove_student() 方法用于添加和删除学生,同时也有一个 display() 方法用于显示班级信息。
我们可以使用这两个类创建一个学生管理系统,例如:
```
s1 = Student("Tom", 18, "Male", "001")
s2 = Student("Alice", 17, "Female", "002")
s3 = Student("Bob", 19, "Male", "003")
class1 = Class("Class A", [s1, s2])
class1.add_student(s3)
class1.display()
```
以上代码创建了三个学生 s1、s2、s3,其中 s1 和 s2 属于一个名为 Class A 的班级,s3 后来加入了这个班级。最后通过调用 class1.display() 方法,可以显示班级信息和所有学生的信息。
阅读全文
相关推荐
















