Python编程之类的应用 学生信息管理系统
class Student:
def __init__(self,No,Name,Gender,Age):
self.No=No
self.Name=Name
self.Gender=Gender
self.Age=Age
def show(self):
print("%-16s %-16s %-8s %-4d" %(self.No,self.Name,self.Gender,self.Age))
class StudentList:
def __init__(self):
self.students = []
def show(self):
print("%-16s %-16s %-8s %-4s" % ("No", "Name", "Gender", "Age"))
for s in self.students:
s.show()
def __insert(self, s):
i = 0
while (i < len(self.students) and s.No > self.students[i].No):
i = i + 1
if (i < len(self.students) and s.No == self.students[i].No):
print(s.No + " 已经存在")
return False
self.students.insert(i, s)
print("增加成功")
return True
def __update(self, s):
flag = False
for i in range(len(self.students)):
if (s.No == self.students[i].No):
self.students[i].Name = s.Name
self.students[i].Gender = s.Gender
self.students[i].Age = s.Age
print("修改成功")
flag = True
break
if (not flag):
print("没有这个学生")
return flag
def __delete(self, No):
flag = False
for i in range(len(self.students)):
if (self.students[i].No == No):
del self.students[i]
print("删除成功")
flag = True
break
if (not flag):
print("没有这个学生")
return flag
def delete(self):
No = input("No=")
if (No != ""):
self.__delete(No)
def insert(self):
No = input("No=")
Name = input("Name=")
while True:
Gender = input("Gender=")
if (Gender == "男" or Gender == "女"):
break
else:
print("Gender is not valid")
Age = input("Age=")
if (Age == ""):
Age = 0
else:
Age = int(Age)
if No != "" and Name != "":
self.__insert(Student(No, Name, Gender, Age))
else:
print("学号、姓名不能为空")
def update(self):
No = input("No=")
Name = input("Name=")
while True:
Gender = input("Gender=")
if (Gender == "男" or Gender == "女"):
break
else:
print("Gender is not valid")
Age = input("Age=")
if (Age == ""):
Age = 0
else:
Age = int(Age)
if No != "" and Name != "":
self.__update(Student(No, Name, Gender, Age))
else:
print("学号、姓名不能为空")
def process(self):
while True:
s = input(">")
if (s == "show"):
self.show()
elif (s == "insert"):
self.insert()
elif (s == "update"):
self.update()
elif (s == "delete"):
self.delete()
elif (s == "exit"):
break
else:
print("show: show students")
print("insert: insert a new student")
print("update: insert a new student")
print("delete: delete a student")
print("exit: exit")
st=StudentList()
st.process()
敲了敲代码,觉得python挺好玩,但是实现一个功能没有那么简单!
什么是面向对象编程?
程序设计的范式,抽象并建立对象模型,因此程序就是不同对象之间相互调用的逻辑。
比如现实世界中Person,Animal,Car之间存在种种关系
如果想在代码中实现对象之间的关系,就需要把抽象的现实世界转化为计算机规定的语言,这就是类的最初由来。
比如人有姓名、性别、年龄等一系列可以描述的内容,在python中就定义为属性,属于某一个类,人中分类比如小王,小明,就是一个个实例,实例化。定义了类之后,就可以对类进行实例化了,实例化是指,把抽象的类,赋予实物的过程。比如,定义好Person这个类后,就可以实例化多个Person出来了。 创建实例使用类名+(),类似函数调用的形式创建。
网友评论