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

发布于:2024-06-03 ⋅ 阅读:(145) ⋅ 点赞:(0)

自学python如何成为大佬(目录):https://blog.csdn.net/weixin_67859959/article/details/139049996?spm=1001.2014.3001.5501

在派生类中定义__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 + "的!")    # 输出的是类属性color

class Apple(Fruit):                      # 定义苹果类(派生类)

    def __init__(self):

        print("我是苹果")

apple = Apple()                          # 创建类的实例(苹果)

apple.harvest()                          # 调用基类的harvest()方法

执行上面的代码后,将显示如图20所示的异常信息。

图20  基类的__init__()方法未执行引起的异常

因此,要让派生类调用基类的__init__()方法进行必要的初始化,需要在派生类使用super()函数调用基类的__init__()方法。例如,在上面代码的第8行代码的下方添加以下代码:

super().__init__()                                    # 调用基类的__init__()方法

注意:在添加上面的代码时,一定要注意缩进的正确性。

运行后将显示以下正常的运行结果:

我是苹果

水果原来是:绿色的!

下面通过一个具体实例演示派生类中调用基类的__init__()方法的具体的应用。

图标 (35)

  实例05  在派生类中调用基类的__init__()方法定义类属性

在IDLE中创建一个名称为fruit.py的文件,然后在该文件中定义一个水果类Fruit(作为基类),并在该类中定义__init__()方法,在该方法中定义一个类属性(用于保存水果默认的颜色),然后在Fruit类中定义一个harvest()方法,再创建Apple类和Sapodilla类,都继承自Fruit类,最后创建Apple类和Sapodilla类的实例,并调用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("\n我是人参果")

        super().__init__(color)                           # 调用基类的__init__()方法

    # 重写harvest()方法的代码

    def harvest(self, color):

        print("人参果是:" + color + "的!")               # 输出的是形式参数color

        print("人参果已经收获……")

        print("人参果原来是:" + Fruit.color + "的!")    # 输出的是类属性color

apple = Apple()                                          # 创建类的实例(苹果)

apple.harvest(apple.color)                                # 调用harvest()方法

sapodilla = Sapodilla("白色")                             # 创建类的实例(人参果)

sapodilla.harvest("金黄色带紫色条纹")                      # 调用harvest()方法

执行上面的代码,将显示如图21所示的运行结果。

图21  在派生类中调用基类的__init__()方法定义类属性


网站公告

今日签到

点亮在社区的每一天
去签到