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)