• Python合集之面向对象(六)


    1.派生类中调用基类的__init__()方法

    在派生类中定义__init__()方法时,不会自动调用基类的__init__()方法。

    例如:定义一个Fruit类,在__init__()方法中创建类属性color,然后再Fruit类中定义一个harvest()方法,在该方法中输出类的属性color的值,在创建继承自Fruit类的Apple类,最后创建Apple类的实例,并调用harvest()方法。

    例如:

    class Fruit:
        def __init__(self,color='绿色'):
            Fruit.color=color
        def harvest(self):
            print("水果原来是:"+Fruit.color+"")
    class Apple(Fruit):
        def __init__(self):
            print("我是苹果")
    apple=Apple()
    apple.harvest()

    执行上面的代码,会弹出相关的异常信息。

    因此,要让派生类调用基类的__init__()方法进行必要的初始化,需要在派生类使用super()函数调用基类的__init__()方法。

    例如:在上面的例子中,修改为:

    class Fruit:
        def __init__(self,color='绿色'):
            Fruit.color=color
        def harvest(self):
            print("水果原来是:"+Fruit.color+"")
    class Apple(Fruit):
        def __init__(self):
            print("我是苹果")
            super().__init__()
    apple=Apple()
    apple.harvest()    
    class Fruit:   #定义水果类(基类)      
        def __init__(self,color='绿色'):
            Fruit.color=color    #定义类属性
        def harvest(self,color):
            print("水果是:"+self.color+"")    #输出的是形式参数color
            print("水果已经收获")
            print("水果原来是:"+Fruit.color+"")   #输出的是类属性color
    class Apple(Fruit):    #定义苹果类(派生类)
        color="红色"
        def __init__(self):
            print("我是苹果")
            super().__init__()   #调用基类的__init__()方法
    class Sapodilla(Fruit):     #定义人参果类(派生类)
        def __init__(self,color):
            print("我是人参果")
            super().__init__(color)    #调用基类的__init__()方法
        def harvest(self,color):
            print("人参果实:"+color+"")   #输出形式参数color
            print("人参果已经收获")
            print("人参果原来是:"+Fruit.color+"")  #输出的是类属性color
    apple=Apple()
    apple.harvest(apple.color)
    sapodilla=Sapodilla("白色")
    sapodilla.harvest("金黄色带紫色条纹")    

    花絮:

    本期的Python 面向对象就分享到这里,下期我们将继续分享Python模块的相关知识,感兴趣的朋友可以关注我。

    同时也可以关注下我的个人 微信订阅号,园子里面的文章也会第一时间在订阅号里面进行推送跟更新。

  • 相关阅读:
    理解Python闭包,这应该是最好的例子
    2021-01-31
    论unity中UI工具与GUI函数
    2021-01-31
    第八届“图灵杯”NEUQ-ACM程序设计竞赛(全题解&&详细)
    第八届“图灵杯”NEUQ-ACM程序设计竞赛个人赛(同步赛)全题解
    Go-快速排序
    网络地址转换NAT原理及其作用
    解析私有IP地址和公网IP地址
    first blog
  • 原文地址:https://www.cnblogs.com/a-mumu/p/14629674.html
Copyright © 2020-2023  润新知