GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • 首页
  • HTML
  • JavaScript
  • CSS
  • React
  • Python3
  • Java
  • C
  • C++
  • C#
  • Go
  • SQL
  • Linux
  • VS Code

This view

  • Original page
  • New address

GeezerVison is showing www.runoob.com — Python super() 函数 | 菜鸟教程

菜鸟教程 -- 学的不仅是技术,更是梦想!

  • Vue3 教程
  • Vue2 教程
  • Bootstrap3
  • Bootstrap4
  • Bootstrap5
  • 机器学习
  • PyTorch
  • TensorFlow
  • Sklearn
  • NLP
  • AI Agent
  • Ollama
  • Coding Plan
Python 基础教程
Python 基础教程 Python 简介 Python 环境搭建 Python 中文编码 Python VS Code Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 Python 循环语句 Python While 循环语句 Python for 循环语句 Python 循环嵌套 Python break 语句 Python continue 语句 Python pass 语句 Python Number(数字) Python 字符串 Python 列表(List) Python 元组 Python 字典(Dictionary) Python 日期和时间 Python 函数 Python 模块 Python 文件I/O Python File 方法 Python 异常处理 Python OS 文件/目录方法 Python 内置函数

Python 高级教程

Python 面向对象 Python 正则表达式 Python CGI 编程 Python MySQL Python 网络编程 Python SMTP Python 多线程 Python XML 解析 Python GUI 编程(Tkinter) Python2.x 与 3​​.x 版本区别 Python IDE Python JSON Python AI 绘画 Python 100例 Python 测验
Python issubclass() 函数
Python bin() 函数

Python super() 函数

Python 内置函数 Python 内置函数


描述

super() 函数是用于调用父类(超类)的一个方法。

super() 是用来解决多重继承问题的,直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)、重复调用(钻石继承)等种种问题。

MRO 就是类的方法解析顺序表, 其实也就是继承父类方法时的顺序表。

语法

以下是 super() 方法的语法:

super(type[, object-or-type])

参数

  • type -- 类。
  • object-or-type -- 类,一般是 self

Python3.x 和 Python2.x 的一个区别是: Python 3 可以使用直接使用 super().xxx 代替 super(Class, self).xxx :

Python3.x 实例:

class A: def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super().add(x) b = B() b.add(2) # 3

Python2.x 实例:

#!/usr/bin/python # -*- coding: UTF-8 -*- class A(object): # Python2.x 记得继承 object def add(self, x): y = x+1 print(y) class B(A): def add(self, x): super(B, self).add(x) b = B() b.add(2) # 3

返回值

无。


实例

以下展示了使用 super 函数的实例:

实例

#!/usr/bin/python # -*- coding: UTF-8 -*- class FooParent(object): def __init__(self): self.parent = 'I\'m the parent.' print ('Parent') def bar(self,message): print ("%s from Parent" % message) class FooChild(FooParent): def __init__(self): # super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类 FooChild 的对象转换为类 FooParent 的对象 super(FooChild,self).__init__() print ('Child') def bar(self,message): super(FooChild, self).bar(message) print ('Child bar fuction') print (self.parent) if __name__ == '__main__': fooChild = FooChild() fooChild.bar('HelloWorld')

执行结果:

Parent
Child
HelloWorld from Parent
Child bar fuction
I'm the parent.

Python 内置函数 Python 内置函数

AI 思考中...
Python issubclass() 函数
Python bin() 函数

4 篇笔记 写笔记

  1. #0

       sme000

      523***[email protected]

      参考地址

    353

    直接用类名调用父类方法在使用单继承的时候没问题,但是如果使用多继承,会涉及到查找顺序(MRO)。一开始看到这句话,不太理解。

    看了这个文章后,明白了。

    我们在学习 Python 类的时候,总会碰见书上的类中有 __init__() 这样一个函数,很多同学百思不得其解,其实它就是 Python 的构造方法。

    构造方法类似于类似 init() 这种初始化方法,来初始化新创建对象的状态,在一个对象呗创建以后会立即调用,比如像实例化一个类:

    f = FooBar()
    f.init()

    使用构造方法就能让它简化成如下形式:

    f = FooBar()

    你可能还没理解到底什么是构造方法,什么是初始化,下面我们再来举个例子:

    class FooBar:
        def __init__(self):
            self.somevar = 42
    
    >>>f = FooBar()
    >>>f.somevar

    我们会发现在初始化 FooBar 中的 somevar 的值为 42 之后,实例化直接就能够调用 somevar 的值;如果说你没有用构造方法初始化值得话,就不能够调用,明白了吗?

    在明白了构造方法之后,我们来点进阶的问题,那就是构造方法中的初始值无法继承的问题。

    例子:

    class Bird:
        def __init__(self):
              self.hungry = True
        def eat(self):
              if self.hungry:
                   print 'Ahahahah'
              else:
                   print 'No thanks!'
    
    class SongBird(Bird):
         def __init__(self):
              self.sound = 'Squawk'
         def sing(self):
              print self.song()
    
    sb = SongBird()
    sb.sing()    # 能正常输出
    sb.eat()     # 报错,因为 songgird 中没有 hungry 特性

    那解决这个问题的办法有两种:

    1、调用未绑定的超类构造方法(多用于旧版 python 阵营)

    class SongBird(Bird):
         def __init__(self):
              Bird.__init__(self)
              self.sound = 'Squawk'
         def sing(self):
              print self.song()

    原理:在调用了一个实例的方法时,该方法的self参数会自动绑定到实例上(称为绑定方法);如果直接调用类的方法(比如Bird.__init__),那么就没有实例会被绑定,可以自由提供需要的self参数(未绑定方法)。

    2、使用super函数(只在新式类中有用)

    class SongBird(Bird):
         def __init__(self):
              super(SongBird,self).__init__()
              self.sound = 'Squawk'
         def sing(self):
              print self.song()

    原理:它会查找所有的超类,以及超类的超类,直到找到所需的特性为止。

    sme000

       sme000

      523***[email protected]

      参考地址

    8年前 (2019-04-23)
  2. #0

       yyYanis

      ysh***[email protected]

    185

    经典的菱形继承案例,BC 继承 A,然后 D 继承 BC,创造一个 D 的对象。

         ---> B ---
    A --|          |--> D
         ---> C ---
    

    使用 super() 可以很好地避免构造函数被调用两次。

    # 思考题正确答案
    
    
    class A():
        def __init__(self):
            print('enter A')
            print('leave A')
    
    
    class B(A):
        def __init__(self):
            print('enter B')
            super().__init__()
            print('leave B')
    
    
    class C(A):
        def __init__(self):
            print('enter C')
            super().__init__()
            print('leave C')
    
    
    class D(B, C):
        def __init__(self):
            print('enter D')
            super().__init__()
            print('leave D')
    
    
    d = D()

    执行结果是:

    enter D
    enter B
    enter C
    enter A
    leave A
    leave C
    leave B
    leave D
    yyYanis

       yyYanis

      ysh***[email protected]

    8年前 (2019-06-11)
  3. #0

       没有昵称

      noe***[email protected]

      参考地址

    18

    建议自己单点调试走一遍就能理解 super 的本质。

    class A(object):
        def __init__(self):
            print("enter A")
            print(self)  # this will print <__main__.D object at 0x...>
            print("leave A")
    class B(A):
        def __init__(self):
            print("enter B")
            print(self)  # this will print <__main__.D object at 0x...>
            super(B, self).__init__()
            print("leave B")
    class C(A):
        def __init__(self):
            print("enter C")
            print(self)  # this will print <__main__.D object at 0x...>
            super(C, self).__init__()
            print("leave C")
    class D(B, C):
        pass
    d = D()
    
    print("""这是D的MRO顺序:""",d.__class__.__mro__,"""super的本质如下:def super(cls, inst):    mro = inst.__class__.mro()    return mro[mro.index(cls) + 1]""")

    运行结果:

    enter B
    <__main__.D object at 0x10a833390>
    enter C
    <__main__.D object at 0x10a833390>
    enter A
    <__main__.D object at 0x10a833390>
    leave A
    leave C
    leave B
    这是D的MRO顺序: (<class '__main__.D'>, <class '__main__.B'>, <class '__main__.C'>, <class '__main__.A'>, <class 'object'>) super的本质如下:def super(cls, inst):    mro = inst.__class__.mro()    return mro[mro.index(cls) + 1]
    没有昵称

       没有昵称

      noe***[email protected]

      参考地址

    7年前 (2020-04-18)
  4. #0

       WillYW

      187***[email protected]

    63

    Python3 中继承遵循广度优先原则:

    class A:
        def __init__(self):
            print("Enter A")
            print(self)
            print("Leave A")
    
    
    class B(A):
        def __init__(self):
            print("Enter B")
            print(self)
            super(B, self).__init__()
            print("Leave B")
    
    
    class C(A):
        def __init__(self):
            print("Enter C")
            print(self)
            super(C, self).__init__()
            print("Leave C")
    
    
    class D(B, C):
        def __init__(self):
            print("Enter D")
            print(self)
            super(D, self).__init__()
            print("Leave D")
    
    
    d = D()

    运行结果:

    Enter D
    <__main__.D object at 0x7fdb02618490>
    Enter B
    <__main__.D object at 0x7fdb02618490>
    Enter C
    <__main__.D object at 0x7fdb02618490>
    Enter A
    <__main__.D object at 0x7fdb02618490>
    Leave A
    Leave C
    Leave B
    Leave D

    1.创建 D 类的对象 d 时,自动调用 D 类的初始化方法 __init()__,此时的 self 指向 D 类创建的实例对象 d;

    2.调用原则:D->B->C->A

    3.在调用到 B 时,首先输出 “Enter B”,但是运行到父类 A 的初始化方法时不立即调用,反而时转向广度优先级高的 C 类,因为 A 类对于 B 类来说是深度遍历。

    WillYW

       WillYW

      187***[email protected]

    6年前 (2020-07-23)

点我分享笔记

取消

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址
分类导航
  • Python / 数据科学
    • Python 教程
    • Python2.x 教程
    • FastAPI 教程
    • Flask 教程
    • Django 教程
    • NumPy 教程
    • Pandas 教程
    • SciPy 教程
    • Matplotlib 教程
    • Dash 教程
    • Jupyter Notebook 教程
    • Pillow 教程
    • 量化交易
    • R 教程
    • Julia 教程
  • AI / 智能开发
    • AI Agent(智能体)
    • AI(人工智能)
    • AI 应用案例
    • Codex 教程
    • Vibe Coding 教程
    • Claude Code
    • OpenCode
    • Skills(技能)
    • Ollama 教程
    • Hermes Agent
    • DeepSeek Harness
    • Pi Agent
    • AI 数学基础
    • TensorFlow 教程
    • PyTorch 教程
    • Scikit-learn 教程
    • 机器 教程
    • LangChain
    • 自然语言处理 NLP
    • OpenCV 教程
    • Selenium 教程
    • Playwright 教程
  • 前端开发
    • HTML 教程
    • HTML5 教程
    • CSS 教程
    • CSS3 教程
    • JavaScript 教程
    • HTML DOM 教程
    • TypeScript 教程
    • AJAX 教程
    • JSON 教程
    • Tailwind CSS 教程
    • Bootstrap4 教程
    • Bootstrap5 教程
    • Foundation 教程
    • Vue.js 教程
    • Vue3 教程
    • React 教程
    • Next.js 教程
    • Three.js 教程
    • AngularJS 教程
    • Angular 教程
    • jQuery 教程
    • jQuery UI 教程
    • jQuery EasyUI 教程
    • ECharts 教程
    • Chart.js 教程
    • Highcharts 教程
    • Google 地图 教程
    • SVG 教程
    • Font Awesome 教程
  • 后端开发
    • Node.js 教程
    • Electron 教程
    • PHP 教程
    • Java 教程
    • Go 教程
    • Rust 教程
    • C# 教程
    • Unity 教程
    • Servlet 教程
    • JSP 教程
    • ASP 教程
    • AppML 教程
    • VBScript 教程
    • Swagger 教程
    • RESTful API 教程
    • Docker 教程
    • Linux 教程
    • ZooKeeper 教程
  • 数据库
    • SQL 教程
    • MySQL 教程
    • PostgreSQL 教程
    • SQLite 教程
    • MongoDB 教程
    • Redis 教程
    • Memcached 教程
  • 移动开发
    • Android 教程
    • Flutter 教程
    • Ionic 教程
    • jQuery Mobile 教程
    • Swift 教程
    • Kotlin 教程
  • DevOps / 工程化
    • Git 教程
    • SVN 教程
    • CMake 教程
    • Maven 教程
    • VS Code 教程
    • Obsidian 教程
    • PyCharm 教程
    • Eclipse 教程
    • Markdown 教程
    • LaTeX 教程
  • 编程语言
    • C 教程
    • C++ 教程
    • Zig 教程
    • Scala 教程
    • Ruby 教程
    • Perl 教程
    • Lua 教程
    • Dart 教程
    • 汇编语言 教程
    • Verilog 教程
  • 计算机基础
    • 计算机组成原理
    • 数据结构与算法
    • C 语言数据结构与算法
    • 设计模式
    • Python 设计模式
    • 正则表达式
    • HTTP 教程
    • TCP/IP 教程
    • 网络协议
    • W3C 教程
  • XML / Web Service
    • XML 教程
    • DTD 教程
    • XML DOM 教程
    • XSLT 教程
    • XPath 教程
    • XQuery 教程
    • XLink 教程
    • XPointer 教程
    • XML Schema 教程
    • XSL-FO 教程
    • Web Service 教程
    • WSDL 教程
    • SOAP 教程
    • RSS 教程
    • RDF 教程
  • .NET
    • ASP.NET 教程
    • MVC 教程
    • Razor 教程
    • Web Forms 教程
    • Web Pages 教程
    • PowerShell 教程
  • 网站建设
    • 网站建设指南
    • 浏览器信息
    • 网站主机教程
    • 网站品质

字节 Coding Plan 限时 9.9 元起,支持 Deepseek-V4、GLM-5.3、Doubao-Seed-Evolving、Kimi-K3。
百度 Dumate 百度推出的桌面级 AI 智能体。 输入激活码送 4000 积分
使用文档
Trae AI 原生开发环境,让编程更高效。新用户注册赠2500积分,管理项目,也交付成果。
Advertisement
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.