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

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

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

super(type[, object-or-type])
super()
  • type -- 类。
  • object-or-type -- 类,一般是 self

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

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) #
class A:
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) #

super(Class, self)要比 super().xxx 灵活,可以跨级调用

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

此处x**2=4
64

__init__里使用super

class A:
def __init__(self,name,age):
self.name=name
self.age=age
def add(self, x):
y = x+1
print(y) class B(A):
def __init__(self):
super(B,self).__init__('wqbin',18)
def add(self, x):
pass
b = B()
print(b.name)

wqbin

最新文章

  1. 日志处理之logging模块
  2. 首次创建maven项目的准备工作
  3. mongoDB研究笔记:复制集数据同步机制
  4. 最基本的session保存法,类似于默认的files方法
  5. Delphi- DLL操作
  6. thinkphp 中 使用七牛云上传
  7. IP defragment
  8. hive建表没使用LZO存储格式,可是数据是LZO格式时遇到的问题
  9. 【Android LibGDX游戏引擎开发教程】第07期:中文字体的显示和绘制(上)
  10. 原生JS实现淘宝无缝轮播
  11. Vmware下centos与windows能ping通并能上网
  12. Promise,我们来实战
  13. Activex、OLE、COM、OCX、DLL之间有什么区别?
  14. Flask 构建微电影视频网站(四)
  15. MacOS下保护浏览器主页和默认搜索
  16. keras 实现人工神经网络
  17. Linux系统级日志系统
  18. Jmeter压力测试工具安装及使用教程
  19. 线程简述(Thread)
  20. C++学习(十)(C语言部分)之 分支语句

热门文章

  1. jwt认证规则
  2. Python面试常考点之深入浅出链表操作
  3. 发明专利定稿&递交申请啦,开心
  4. echart tooltip问题(鼠标放上去显示所有和显示当个)
  5. vue入门:(计算属性和侦听器)
  6. JSP中的普通路径写法
  7. 【Spring Cloud】 总结
  8. Flume下读取kafka数据后再打把数据输出到kafka,利用拦截器解决topic覆盖问题
  9. axios表单提交,delete,get请求(待完善)
  10. vue +echarts树状图