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模块的相关知识,感兴趣的朋友可以关注我。

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

posted @ 2021-04-07 21:26  @睦  阅读(124)  评论(0编辑  收藏  举报