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