Doubt (1) ----- What does super(XXX, self).__init__() mean?

Good articles shouldn't be buried, and then I retouched them, and they should be known to more people! ! !
Reprinted : https://blog.csdn.net/zyh19980527/article/details/107206483/

I believe you have seen the following code on many occasions, especially when writing neural network code:

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)
        self.conv2 = nn.Conv2d(6, 16, 5)
        # an affine operation: y = Wx + b
        self.fc1 = nn.Linear(16 * 5 * 5, 120)
        self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(84, 10)

    def forward(self, x):
        # 2x2 Max pooling
        x = F.max_pool2d(F.relu(self.conv1(x)), (2, 2))
        # 如果是方阵,则可以只使用一个数字进行定义
        x = F.max_pool2d(F.relu(self.conv2(x)), 2)
        x = x.view(-1, self.num_flat_features(x))
        x = F.relu(self.fc1(x))
        x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

What you may be a little confused at first is what the following three lines of code are used for. To understand these three lines of code, you need to know three things:

  • self parameter
  • __init__ () method
  • super(Net, self).init()

Next, I will explain them one by one.

One, self parameter

Self refers to the instance itself. It is stipulated in the Python class that the first parameter of the function is the instance object itself, and it is customary to write its name as self, that is, the first parameter of the method in the class must be self, and cannot be omitted.
I think three things about self are very important:

  • self refers to the instance itself, not the class
  • self can be replaced with this, but don’t write like this
  • The self in the method of the class cannot be omitted

First of all, the first point self refers to the instance itself, not the class

class Person():
    def eat(self):
        print(self)

Bob=Person()
Bob.eat()
print(Person)

Insert picture description here
Looking at the output, we can see that self refers to an instance object, not a class

The second point is that self can be replaced with this, but don’t write it like that. In fact, I understand that self is equivalent to this in Java. Let’s try to change it.

class Person():
    def eat(this):
        print(this)

Bob=Person()
Bob.eat()
print(Person)

Insert picture description here
There is no error, but you still use self according to the specification. The self in the
third point of the method cannot be omitted. Look at the following code, pycharm automatically prompts that the parameter self is required.
Insert picture description here

Two, __init__ () method

After creating a class in python, a \ __init__ () method is usually created, which will be automatically executed when an instance of the class is created. The \ __ init__ () method must include a self parameter, and if it is the first parameter.

For example, the code in the following example, when we instantiate Bob this object, the \ __ init__ () method has been automatically executed, but if it is not the \ __ init__ () method, for example, the eat() method, then there must be only Call to execute

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

Insert picture description here

For another example, in the following code, if another parameter name needs to be passed in the \ __init__ () method, but we did not pass in name when creating an instance of Bob, then the program will report an error saying that we are missing one\ The parameter of the __ init__ () method, because the \ __ init__ () method is automatically executed in the process of creating an instance. At this time, it is found that there is no name parameter, and an error must be reported!

class Person():
    def __init__(self,name):
        print("是一个人")
        self.name=name
    def eat(self):
        print("%s要吃饭" %self.name)

Bob=Person()
Bob.eat()

Insert picture description here
It won't happen after Bob is passed in, and the eat method can also use the name parameter.

class Person():
    def __init__(self,name):
        print("是一个人")
        self.name=name
    def eat(self):
        print("%s要吃饭" %self.name)

Bob=Person('Bob')
Bob.eat()

Insert picture description here
In this way, we actually know more clearly what needs to be defined in the \ __init__ () method. It is hoped that some operations are available when creating an instance. For example, the following code should actually use money This quantity is defined in the \__init__ () method, so that there is no need to execute the qian() method after executing the eat() method. In other words, when we write neural network code, some network structure settings are best placed in the \ __init__ () method.

class Person():
    def __init__(self,name):
        print("是一个人")
        self.name=name
    def eat(self,money):
        print("%s要吃饭" %self.name)
        self.money=money
    def qian(self):
        print("花了%s元" %self.money)

Bob=Person('Bob')
Bob.eat(12)
Bob.qian()

Three, super(Net, self).__init__()

The super(Net, self).__init__() in Python means to first find the parent class of Net (for example, the class NNet), and then convert the object self of class Net to the object of class NNet, and then the "converted" class NNet The object calls its own init function. In fact, the simple understanding is that the subclass puts the __init__() of the parent class in its own __init__(), so that the subclass has those things of the parent class's __init__().

Looking back at our top code, the Net class inherits nn.Module, and super(Net, self).__init__() initializes the attributes inherited from the parent class nn.Module. And the initialization method of nn.Module is used to initialize the inherited properties.

class Net(nn.Module):

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

That is to say, the subclass inherits all the properties and methods of the parent class, and the properties of the parent class will naturally be initialized with the methods of the parent class.
Give an example to help everyone understand:

class Person:
    def __init__(self,name,gender):
        self.name = name
        self.gender = gender
    def printinfo(self):
        print(self.name,self.gender)

class Stu(Person):
    def __init__(self,name,gender,school):
        super(Stu, self).__init__(name,gender) # 使用父类的初始化方法来初始化子类
        self.school = school
    def printinfo(self): # 对父类的printinfo方法进行重写
        print(self.name,self.gender,self.school)

if __name__ == '__main__':
    stu = Stu('djk','man','nwnu')
    stu.printinfo()

Insert picture description here

Of course, if the logic of initialization is different from that of the parent class, you can reinitialize it yourself without using the method of the parent class. such as:

class Person(object):
    def __init__(self,name,gender,age):
        self.name = name
        self.gender = gender
        self.age = age
 
class Student(Person):
    def __init__(self,name,gender,age,school,score):
        #super(Student,self).__init__(name,gender,age)
        self.name = name.upper()  
        self.gender = gender.upper()
        self.school = school
        self.score = score
 
s = Student('Alice','female',18,'Middle school',87)
print s.school
print s.name

Guess you like

Origin blog.csdn.net/dongjinkun/article/details/114575998