0

I am studying the code of Fast Depth and I am wondering what is the meaning of writing the __init__ method of the class like this:

class MobileNet(nn.Module):
    def __init__(self, decoder, output_size, in_channels=3, pretrained=True):

        super(MobileNet, self).__init__()

or this (always the same)

class MobileNetSkipAdd(nn.Module):
    def __init__(self, output_size, pretrained=True):

        super(MobileNetSkipAdd, self).__init__()

I don't understand the usage of the super() function, where it is called the class itself.

martineau
  • 119,623
  • 25
  • 170
  • 301
etnamaid
  • 19
  • 1
  • 7

2 Answers2

1

The super function gets you the parent class, in your example nn.Module. Note that since Python 3 you can just say:

super().__init__()

When used with __init__, it lets you perform the initialization code defined in the parent, on the instance you're creating. It's usually followed by initialization code that is specific to this subclass.

Since the MobileNet subclass is a kind of nn.Module, a specialized case of the more general nn.Module if you will, it makes sense to perform the general initialization first, and then the specific initialization.

joao
  • 2,220
  • 2
  • 11
  • 15
0

super takes two arguments:

  1. The class to use as the starting point in the MRO for attribute lookup
  2. The object that supplies the MRO and is ultimately used to look the attribute up on.

You virtually always want to use the class that super statically appears in, as well as the object the current method received as the default. Therefore, in Python 3, the compiler was changed to determine these two values automatically, allowing you to simply write super().__init__ instead of providing the arguments explicitly.

Note that it's not as simple as defining default argument values, like

def super(x=..., y=...):

because the "defaults" can only be determined in the context of where super is called, not something you know when super is defined. That's why it requires special compiler support.

chepner
  • 497,756
  • 71
  • 530
  • 681