python|python super用法 2018-01-28
新式类,经典类
python3之后均称为新式类,默认继承object类
Python2.x版本分为:分新式类与经典类
新式类:每个类都继承于一个基类,可以是自定义类或者其它类,默认承于object
【python|python super用法 2018-01-28】旧式类:不继承object类
mro算法:方法解析顺序
新式类中采用广度算法,经典类中采用深度算法
super 仅用于新式类
super 用法
In Python 3 and above, the syntax for super is:
super().methoName(args)
Whereas the normal way to call super (in older builds of Python) is:
super(subClass, instance).method(args)
单个继承初始化
class MyParentClass(object):def __init__(self):pass
class SubClass(MyParentClass):def __init__(self):MyParentClass.__init__(self)
If we were using Python 2, we would write the subclass like this (using the super function):
class SubClass(MyParentClass):
def __init__(self):
super(SubClass, self).__init__()
The same code is slightly different when writing in Python 3, however.
class MyParentClass():def __init__(self):pass
class SubClass(MyParentClass):def __init__(self):
super()
Now, keep in mind most classes will also have arguments passed to them. The super function will change even more when that happens.
It will look like the following:
class MyParentClass():def __init__(self, x, y):pass
class SubClass(MyParentClass):def __init__(self, x, y):super().__init__(x, y)
In Python 3 and above, the syntax for super is:
super().methoName(args)
Whereas the normal way to call super (in older builds of Python) is:
super(subClass, instance).method(args)
新式类中mro:广度搜索
super的原理:遍历当前类的mro列表,查找含有当前方法的第一个类,找到则用类调用方法,退出
文章图片
Demo
文章图片
推荐阅读
- python学习之|python学习之 实现QQ自动发送消息
- 逻辑回归的理解与python示例
- python自定义封装带颜色的logging模块
- 【Leetcode/Python】001-Two|【Leetcode/Python】001-Two Sum
- Python基础|Python基础 - 练习1
- Python爬虫|Python爬虫 --- 1.4 正则表达式(re库)
- Python(pathlib模块)
- python青少年编程比赛_第十一届蓝桥杯大赛青少年创意编程组比赛细则
- Python数据分析(一)(Matplotlib使用)
- Python|Python 9.20