Python——继承、初始化

super(Net, self).init()

学习神经网络时,代码中的super(Net, self).init(),这是干什么的呢?

import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()
        # 输入图像channel:1;输出channel:6;5x5卷积核
        self.conv1 = nn.Conv2d(1, 6, 5)

1.这一句是继承的意思,Net继承了nn.Module

class Net(nn.Module):

2.然后是初始化,初始化是什么意思呢?也就是说,只要实例化Net,def __init __() 的内容就会被执行。而其他方法需要调用才会执行

class Net(nn.Module):

    def __init__(self):

这里举个例子,Bob=Person()就是实例化,print(“是一个人”)会自动执行。而rint(“要吃饭” )不会自动执行,只有调用时候才会执行。

class Person():
    def __init__(self):
        print("是一个人")
    def eat(self):
        print("要吃饭" )
Bob=Person()

3.紧接着是执行父类的初始化,super(Net, self).init()是执行父类的初始化(也就是执行nn.Module的初始化),没有super(Net, self).init()的后果就是nn.Module的方法可以用,但是nn.Module初始化的内容用不了

class Net(nn.Module):

    def __init__(self):
        super(Net, self).__init__()

举个例子,去掉super(son,self).init()时候,前两句执行成功,第三句报错了AttributeError: ‘son’ object has no attribute ‘x’

class farther(object):
    def __init__(self):
        self.x = '这是属性'
        
    def fun(self):
        print(self.x)
        
    def g(self):
        print('你好!')

        
class son(farther):
    def __init__(self):
#         super(son,self).__init__()
        print('实例化执行')
            
test = son()
test.g()
test.fun()

输出结果

实例化执行
你好!
AttributeError: 'son' object has no attribute 'x'

取消注释super(son,self).init()后输出结果为

实例化执行
你好!
这是属性

猜你喜欢

转载自blog.csdn.net/weixin_44823313/article/details/114758039