面向对象练习:
"""侧重于面向对象"""
01.自己写一个Student类,此类的对象有属性name, age, score, 用来保存学生的姓名,年龄,成绩:
1) 写一个函数input_student读入n个学生的信息,用对象来存储这些信息(不用字典),并返回对象的列表
2) 写一个函数output_student 打印这些学生信息(格式不限)
class Student():
def __init__(self, name, age, score):
self.name = name
self.age = age
self.score = score
def input_student():
L = []
while True:
name = input("姓名:")
if not name:
break
age = input("年龄:")
score = input("成绩:")
s = Student(name, age, score)
L.append(s)
return L
def output_student(lst):
for i in lst:
print("姓名:%s 年龄:%s 成绩:%s" % (i.name, i.age, i.score))
def main():
L = input_student()
output_student(L)
main()
02.定义一个类Huamn(人类),定义函数input_human录入信息,main调用显示信息:
有三个属性:姓名name,年龄age,家庭住址address (可以省略没有)
有方法:show_info 用来显示人的信息,update_age用来让这个人的年龄增加一岁
class Huamn():
total_count = 0
def __init__(self, name, age, address=None):
self.name = name
self.age = age
self.address = address
self.__class__.total_count += 1
def show_info(self):
print("姓名:%s 年龄:%s 地址:%s" % (self.name, self.age, self.address))
def updata_age(self):
self.age += 1
@classmethod
def get_huamn_count(cls):
return cls.total_count
def __del__(self):
self.__class__.total_count -= 1
def input_human():
L = []
while True:
name = input("姓名:")
if not name:
break
age = int(input("年龄:") or ‘0‘)
address = input("地址:")
s = Huamn(name, age, address)
L.append(s)
return L
def main():
L = input_human()
for obj in L:
obj.show_info() # 列出所有人的信息
for obj in L:
obj.updata_age() # 让所有人都长一岁
for obj in L:
obj.show_info() # 再次列表所有人的信息
print("当前总人数是%s" % Huamn.get_huamn_count())</