写一个班级类,属性:班级名、学生;功能:添加学生、查找学生
class Class:
"""班级类"""
def __init__(self, name='', student=[]):
self.class_name = name
self.students = student
def add_student(self):
while True:
name = input('name(input 0 to exit):')
if name == '0':
return
sex = input('sex:')
age = int(input('age:'))
# 根据输入的信息创建学生对象
stu = Student(name, sex, age)
# 添加学生
self.students.append(stu)
def find_student(self, name):
for index in range(len(self.students)):
if name == self.students[index].name:
return self.students[index]
class Student:
"""学生类"""
def __init__(self, name='', sex='', age=0):
self.name = name
self.sex = sex
self.age = age
def __str__(self):
return 'name:%s sex:%s age:%d' % (self.name, self.sex, self.age)
if __name__ == '__main__':
cls1 = Class('py1805')
cls1.add_student()
for index in range(len(cls1.students)):
print(cls1.students[index])
while True:
name = input('find student by name(input 0 to exit):')
if name == '0':
break
stu = cls1.find_student(name)
print(stu)
结果:
name(input 0 to exit):张三
sex:男
age:20
name(input 0 to exit):李四
sex:男
age:25
name(input 0 to exit):王五
sex:女
age:19
name(input 0 to exit):0
name:张三 sex:男 age:20
name:李四 sex:男 age:25
name:王五 sex:女 age:19
find student by name(input 0 to exit):张三
name:张三 sex:男 age:20
find student by name(input 0 to exit):李四
name:李四 sex:男 age:25
find student by name(input 0 to exit):王五
name:王五 sex:女 age:19
find student by name(input 0 to exit):0
Process finished with exit code 0