python super用法 2018-01-28
新式类,经典类
python3之后均称为新式类,默认继承object类
Python2.x版本分为:分新式类与经典类
新式类:每个类都继承于一个基类,可以是自定义类或者其它类,默认承于object
旧式类:不继承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