zoukankan      html  css  js  c++  java
  • 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模块的相关知识,感兴趣的朋友可以关注我。

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

  • 相关阅读:
    字符串个数的麻烦
    最长单调递增子序列LIS(《算法导论》15.4-5题)
    LCS问题
    关于nextLine()与nextInt()
    调用内部类里,在静态类中调用动态方法的问题
    RTL底层释放或回收对象
    软件需求分、架构设计与建模最佳实践
    Spring@Autowired java.lang.NullPointerException 空指针
    MAC下安装REDIS和REDIS可视化工具RDM并连接REDIS
    Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.apache.catalina.connector.CoyoteWriter and no properties discovered to create BeanSerializer
  • 原文地址:https://www.cnblogs.com/a-mumu/p/14629674.html
Copyright © 2011-2022 走看看