Python中super()函数详解如何使用?

2026-04-30 14:151阅读0评论SEO基础
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计1792个文字,预计阅读时间需要8分钟。

Python中super()函数详解如何使用?

目录+实战场景+实战编码+单继承使用+实战场景+常见问题学习Python+面向对象时,阅读他人代码,会发现一个super()函数。这个函数的作用到底是什么呢?super()函数的作用是用于调用父类的方法。具体用途如下:在类名中,调用super()可以返回当前类的父类。在方法名中,调用super()可以调用父类中相同方法名的方法。

例如:在类名中:class Parent: def __init__(self): print(Parent init)

class Child(Parent): def __init__(self): super().__init__() print(Child init)执行Child类的构造函数,会先打印Parent init,再打印Child init。

在方法名中:class Parent: def method(self): print(Parent method)

class Child(Parent): def method(self): super().method() print(Child method)执行Child类的method方法,会先打印Parent method,再打印Child method。

阅读全文

本文共计1792个文字,预计阅读时间需要8分钟。

Python中super()函数详解如何使用?

目录+实战场景+实战编码+单继承使用+实战场景+常见问题学习Python+面向对象时,阅读他人代码,会发现一个super()函数。这个函数的作用到底是什么呢?super()函数的作用是用于调用父类的方法。具体用途如下:在类名中,调用super()可以返回当前类的父类。在方法名中,调用super()可以调用父类中相同方法名的方法。

例如:在类名中:class Parent: def __init__(self): print(Parent init)

class Child(Parent): def __init__(self): super().__init__() print(Child init)执行Child类的构造函数,会先打印Parent init,再打印Child init。

在方法名中:class Parent: def method(self): print(Parent method)

class Child(Parent): def method(self): super().method() print(Child method)执行Child类的method方法,会先打印Parent method,再打印Child method。

阅读全文