百度飞桨领航团python零基础训练营第五次作业解析(python面向对象)
课程链接:https://aistudio.baidu.com/aistudio/course/introduce/7073(加入课程链接)
https://aistudio.baidu.com/aistudio/education/lessonvideo/1052903(第五次课程链接)
第1题
定义Rugby为Athlete的子类,并增加子类自己的属性squat.
1题 定义Rugby为Athlete的子类,并增加子类自己的属性squat。(5分)
class Athlete:
def __init__(self,a_name,a_dob=None,a_times=[]):
self.name = a_name
self.dob = a_dob
self.times = a_times
def top3(self):
return sorted(set([self.sanitize(t) for t in self.times]))[0:3]
def sanitize(self,time_string):
if '-' in time_string:
splitter = '-'
elif ':' in time_string:
splitter = ':'
else:
return (time_string)
(mins,secs) = time_string.split(splitter)
return (mins+'.'+secs)
def get_coach_data(filename):
with open(filename) as f:
line = f.readline()
return line.strip().split()
#代码1,定义Rugby类继承Athlete
class Rugby(Athlete):
def __init__(self,a_name,a_dob,a_squat,a_times):
#代码2,调用父类的构造方法,传递的参数为a_dob、a_times
Athlete.__init__(self,a_name,a_dob,a_times)
#代码3,将a_squat赋值给类属性squat
self.squat = a_squat
第2题
定义otherAthlete类为Athlete类的子类,重写top3方法(允许重复的时间)
#2题 定义OtherAthlete类为Athlete类的子类,重写top3方法(允许重复的时间) (5分)
#代码1,定义OtherAthlete类继承Athlete
class otherAthlete(Athlete):
def __init__(self,a_name,a_bod,a_squat,a_times):
Athlete.__init__(self,a_name,a_squat,a_times);
self.squat = a_squat
def top3(self):
#代码2,定义无参数top3函数,对self.times属性应用统一化和排序功能
return sorted([self.sanitize(t) for t in self.times ])[0:3]
第3题
定义print_rugby函数,以多态的方式调用子类属性和方法。
#3题 定义print_rugby函数,以多态的方式调用子类属性和方法 (5分)
def get_coach_data(filename):
with open(filename) as f:
line = f.readline()
return line.strip().split(',')
loren = get_coach_data('mywork/loren.txt')
mark = get_coach_data('mywork/mark.txt')
loren = Rugby(loren.pop(0),loren.pop(0),loren.pop(0),loren)
mark = otherAthlete(mark.pop(0),mark.pop(0),mark.pop(0),mark)
def print_rugby(athlete):
print(athlete.name)
print(athlete.dob)
print(athlete.squat)
print(athlete.top3())
#代码2,调用print_rugby函数,参数为loren
print_rugby(loren)
#代码3,调用print_rugby函数,参数为mark
print_rugby(mark)
loren
2011-11-3
270
['3.11', '3.23', '3.59']
mark
300
300
['3.11', '3.11', '3.23']
第4题
本题主要考察父类,子类,继承的相关知识。
#4题 有两个父类,一个Father,一个Mother,定义Child类共同继承这两个父类,子类调用父类的属性和方法 (5分)
class Father():
def __init__(self):
self.color = 'black'
def talk(self):
print("---爸爸的表达能力---")
class Mother():
def __init__(self):
self.height = 170
def smart(self):
print("---妈妈聪明的头脑---")
#代码1,定义Child类继承Father和Mother
class Child(Father,Mother):
def __init__(self):
#代码2,调用Mother类的的__init__方法
Father.__init__(self)
Mother.__init__(self)
#代码3,创建Child类的对象child,调用无参数的构造方法
child1 = Child()
#代码4,通过child调用父类的smart方法
child1.smart()
#代码5,通过child打印父类的color属性
print(child1.color)
---妈妈聪明的头脑---
black
这次python速成营,学习到python基础语法,数据类型,流程控制,组合数据类型,函数等知识,还学习到面向对象,继承与多态,以及python基础类库。涵盖了python的全面基础知识。有的知识在python大学基础课程里还没有涉及到,收获颇多。希望年后可以安排python深度学习入门课程,能够继续学习。
辛苦所有的讲师和助教老师了,课程从讲授到后期答疑,作业辅导都非常到位,非常不错的课程。会推荐更多python人来学习的。感谢@Molly老师@朱子英老师@助教--GT2号 @助教-KevinPang