Python笔记-super().init(root)的作用

假设我们有一个名为Animal的父类,它有一个属性color,在其构造函数__init__中被初始化:

class Animal:
    def __init__(self, color):
        self.color = color

现在,我们想创建一个Animal的子类,名为DogDog类有自己的属性name,但我们也希望它能继承Animal类的color属性。所以,我们在Dog类的构造函数中调用super().__init__(color)

class Dog(Animal):
    def __init__(self, color, name):
        super().__init__(color)
        self.name = name

在这个例子中,super().__init__(color)就是在调用Animal类的构造函数,这样Dog类就能继承Animal类的color属性。如果我们没有在Dog类的构造函数中调用super().__init__(color),那么Dog类就不会有color属性,因为Animal类的构造函数没有被调用。

总而言之super().__init__(root)的作用就是在子类中调用父类的构造函数,以便子类能继承父类的属性和方法。

相关推荐

  1. Python笔记-super().init(root)作用

    2024-02-23 03:42:01       55 阅读
  2. python中星号(*)作用

    2024-02-23 03:42:01       56 阅读
  3. python装饰器作用

    2024-02-23 03:42:01       44 阅读
  4. Python名称空间和作用

    2024-02-23 03:42:01       60 阅读
  5. Python函数中*args,**kwargs作用与用法

    2024-02-23 03:42:01       61 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-23 03:42:01       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-23 03:42:01       106 阅读
  3. 在Django里面运行非项目文件

    2024-02-23 03:42:01       87 阅读
  4. Python语言-面向对象

    2024-02-23 03:42:01       96 阅读

热门阅读

  1. git常用命令记录

    2024-02-23 03:42:01       44 阅读
  2. Unity架构师经验分享:基于状态机的逻辑控制

    2024-02-23 03:42:01       54 阅读
  3. golang GOPATH 和GOROOT

    2024-02-23 03:42:01       54 阅读
  4. 【动态规划题目讲解】洛谷P8392 Uplifting Excursion

    2024-02-23 03:42:01       54 阅读
  5. 函数——递归4(c++)

    2024-02-23 03:42:01       52 阅读
  6. Factory Method

    2024-02-23 03:42:01       52 阅读
  7. TCP协议

    TCP协议

    2024-02-23 03:42:01      40 阅读
  8. springboot使用PageHelper

    2024-02-23 03:42:01       58 阅读
  9. 分享一个治疗神经痛的药方

    2024-02-23 03:42:01       47 阅读
  10. python子域名收集工具

    2024-02-23 03:42:01       47 阅读
  11. QT TCP通讯客户端与服务端

    2024-02-23 03:42:01       51 阅读
  12. PTA笔记

    2024-02-23 03:42:01       55 阅读