一、子类、父类、超类的关系
Son直接继承Parent,二者之间叫做子类和父类
Parent直接继承Grandparent,二者之间叫做子类和父类
Son间接继承Grandparent,Grandparent是Son的超类
二、继承方式
在子类中用super()函数调用父类/超类的同名方法,若子类和父类同时具有被调用的方法,优先调用父类中的方法。
两种写法:
(1)Python2.x 及以上 适用,
def 函数名(self):
super( 所在子类的类名,self).父类/超类中的同名函数()
(2)Python3.x 适用,
def 函数名(self):
super().父类/超类中的同名函数()
另注意:
函数名不一定是__init__(),super()函数不仅可以调用__init__()函数,父类/超类中的其他函数如forwar()皆可被调用。
class Baseline(nn.Module):
def __init__(self):
super(Baseline, self).__init__()
def forward(self):
super(Baseline, self).forward()
# nn.Module 是父类,Baseline是子类,在Baseline的函数中调用父类的同名函数