新式類,經典類
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