百度飞桨领航团零基础Python速成营]类对象笔记:面向对象中的继承

百度飞桨领航团零基础Python速成营,,传送门来一个https://aistudio.baidu.com/aistudio/course/introduce/7073


前言

参加了百度飞桨领航团零基础Python速成营,对于菜鸟老说还是相当有帮助的,推荐看到这篇文章的人一起来学习,传送门来一个https://aistudio.baidu.com/aistudio/course/introduce/7073,希望每个菜鸟都能找到自己的鸟巢,然后慢慢能飞起来呀

一、继承

定义:

class 子类名(父类名):

情况1,如果子类有新增的属性,那么需要在子类__init方法中,调用父类的__init__

情况2,如果子类没有新增的属性,子类不需要写__init__方法

使用:
对象名 = 子类名(参数)

继承的好处:代码重用,升级功能(重写),新增功能(新的方法)

(一)继承的使用步骤

案例说明:橄榄球教练Roger,拿出了自己的数据结构,我们的队员除了速度训练,还需要进行力量的练习。既然你的类表现的不错,我能不能用呢?

1.文件的读取

def get_coach_data(filename):
    with open(filename) as f:
        line = f.readline()
    return line.strip().split(',')

2.定义父类

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)

3.子类继承父类的写法

#定义橄榄球运送员类
class Rugby(Athlete):
    def __init__(self,a_name,a_bod,a_squat,a_times):
        #调用父类__init__
        Athlete.__init__(self,a_name,a_bod,a_times)
        #深蹲次数
        self.squat = a_squat
    # 继承后下面两个函数就在Rugby类中,只是看不到而已
    # 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)

说明:这里class Rugby(Athlete):这句话就表示子类Rugby继承了父类Athlete。

注意:如果Rugby中的参数与父类Athlete参数完全相同,那么这个时候不需要定义def __init__,但是本题中,Rugby中的参数比父类多了一个a_squat,那么就需要调用父类的__init__并且重新录入自己的self.squat,继承的好处在于不需要重新定义top3,sanitize方法,直接可以使用父类的就可以了。

 

4.测试一下

oren = get_coach_data('mywork/loren.txt')
rugby = Rugby(loren.pop(0),loren.pop(0),loren.pop(0),loren)
print('姓名:%s,生日:%s,深蹲:%s个,最块的3次成绩:%s' %(rugby.name,rugby.dob,rugby.squat,rugby.top3()))

测试结果:

姓名:loren,生日:2011-11-3,深蹲:270,深蹲:3.59个,最慢的3次成绩:['4.11', '4.21', '4.21']

数据资源在:链接:https://pan.baidu.com/s/19yPyE2y38bNbhI2NIzLWpQ      

提取码:5x0j

 

(二)方法的重写

如果发生新的需求,如:作为橄榄球队的教练,我不太在意最快的3个记录,top3我只想知道3次最长时间记录就可以了,重复也行。

1.定义

子类方法与父类方法完全相同,子类若重写了父类的方法,则子类对象调用方法时就是调用的自己类中重新的方法。

2.使用方法

class OtherAthlete(Athlete):
    def __init__(self,a_name,a_bod,a_squat,a_times):

        Athlete.__init__(self,a_name,a_bod,a_times)

        self.squat = a_squat
    def top3(self):
        return sorted([self.sanitize(t) for t in self.times])[0:3]

这里建立了新的子类OtherAthlete,在新子类中重新定义了top3的方法,这个时候,就不再使用父类的top3方法了。

3.测试一下:

mark = get_coach_data('mywork/mark.txt')
mark = OtherAthlete(mark.pop(0),mark.pop(0),mark.pop(0),mark)
print('姓名:%s,生日:%s,深蹲:%s个,最快的3次成绩:%s' %(mark.name,mark.dob,mark.squat,mark.top3()))

运行结果为:

姓名:mark,生日:2010-2-4,深蹲:300个,最快的3次成绩:['3.11', '3.11', '3.23']

(三)多继承

和生活中的案例一样,比如子女会继承父母两个人的。这里子类也会继承两个父类。

1.使用方法

class Father(): 
    def talk(self):
        print("---爸爸的表达能力---")

class Mother():
    def smart(self):
        print("---妈妈聪明的头脑---")

class Child(Father,Mother):
    pass

child1 = Child()
child1.talk()
child1.smart()

运行结果:

---爸爸的表达能力---
---妈妈聪明的头脑---

这里class Child(Father,Mother):这句话就是表是Child子类继承了两个父类,分别是:Father,Mother。

2.多继承中的注意点

在多继承中,需要注意的是父类中尽量避免包含出现相同名字的属性和方法。

案例一:

#多个父类有相同的属性或方法名,这种情况应该避免
class Father(): 
    def __init__(self):
        self.color = 'black'

    def talk(self):
        print("---爸爸的表达能力---")

class Mother():
    def __init__(self):
        self.color = 'white'
    def talk(self):
        print("--妈妈也能表达")
    def smart(self):
        print("---妈妈聪明的头脑---")

class Child(Father,Mother):
    pass

child1 = Child()

print(child1.color)

这里运行结果为:black

我们可以发现Father和Mother中都包含color的属性,那么Child继承谁的呢?这里要看class Child(Father,Mother):谁在前就继承谁的属性。

案例二:

class Father(): 
    def __init__(self):
        self.color = 'Black'
    def talk(self):
        print("---爸爸的表达能力---")

class Mother():
    def __init__(self):
        self.color = 'White'
        self.height = 170
    def smart(self):
        print("---妈妈聪明的头脑---")


class Child(Father,Mother):
#代码1,定义Child类继承Father和Mother
    def __init__(self):
        Father.__init__(self)
        Mother.__init__(self)
        
    #pass
#代码3,创建Child类的对象child,调用无参数的构造方法
child=Child()


#代码4,通过child调用父类的smart方法
child.smart()
child.talk()  #在调用一个Father父类中的方法


#代码5,通过child打印父类的color属性
print(child.color) #如果多继承下两个相同的属性,比如Father下也有color,在Mother中也有color,那么当 def __init__(self):不定义的时候,看class Child(Father,Mother):这里面Father,Mother谁在前,但是若def __init__(self):定义的时候,看 Mother.__init__(self)和Father.__init__(self)谁在后
        

这里运行结果为:While

为什么同样是class Child(Father,Mother),这里就是继承了Mother的呢,是因为通过观察可以知道这里子类定义了def __init__(self),若def __init__(self):定义的时候,看 Mother.__init__(self)和Father.__init__(self)谁在后,因为程序是顺序执行的,谁在后就执行谁的,这里Mother在后,因此Child就结成了Mother中的color,因此child,color的结果为:While
        


总结

在面向对象中,封装、继承、多态是三种重要特点,本文着重介绍了继承,当然还比较基础,仅介绍了子类如果继承父类,重新方法的操作以及多继承的使用,这里要推荐大家学习百度飞桨领航团零基础Python速成营的课程,传送门再来一次:https://aistudio.baidu.com/aistudio/course/introduce/7073  亲测,真的课不错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值