class Foo():
def __init__(self, x):
print("this is class of Foo.")
print("Foo类属性初始化")
self.f = "foo"
print(x)
class Children(Foo):
def __init__(self):
y = 1
print("this is class of Children.")
print("Children类属性初始化")
super(Children, self).__init__(y) # 进入`Foo类`中,向`Foo类`中传入参数`y`,同时初始化`Foo类属性`。
a = Children()
print(a)
print(a.f)
上面代码,执行顺序:
创建实例化对象:a = Children()
执行a:print(a)
-->进入Childern类
-->初始化Childern
类参数,执行def __init__(self):
下函数 -->进入Children父类Foo
,传入参数y
并初始化父类Foo
参数super(Children, self).__init__(y)
,执行Foo
中的参数初始化
输出结果:
this is class of Children.
Children类属性初始化
this is class of Foo.
Foo类属性初始化
1
foo
类在神经网络中的应用
class Net(nn.Module):
def __init__(self):
print("this is Net")
self.a = 1
super(Net, self).__init__()
def forward(self, x):
print("this is forward of Net", x)
class Children(Net):
def __init__(self):
print("this is children")
super(Children, self).__init__()
a = Children()
a(1)
输出:
this is children
this is Net
this is forward of Net 1
上面代码执行顺序:
创建实例化对象:a = Children()
执行a:进入Childern类
-->初始化Childern类参数
,执行def __init__(self):
内函数 -->进入Children父类Net
,传入参数y
并初始化父类Net
参数super(Children, self).__init__()
,执行Foo
中的参数初始化 -->传入参数并执行父类Net
的forward()函数a(1)