Loading

python类的执行顺序

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)

posted @ 2021-03-07 21:47  Guang'Jun  阅读(2399)  评论(0编辑  收藏  举报