Search code examples
pythonclasstorch

Why does this line not instantiate a class?


I am a python beginner going over a tutorial on neural networks and the PY torch module. I don't quite understand the behavior of this line.

import torch.nn as nn

loss = nn.MSELoss()

print(loss)

>>MSELoss()

Since nn.MSELoss is a class, why does calling it to the variable loss not instantiate it as a class object? What type of code is in the class MSELoss that allows it to achieve this behavior?


Solution

  • When you print some object you're actually calling its __str__ method in Python or if it isn't defined then __repr__ (from representation).

    In your case, it's about normal class, but its __repr__ has been overriden:

    def __repr__(self):
        # We treat the extra repr like the sub-module, one item per line
        extra_lines = []
        extra_repr = self.extra_repr()
        # empty string will be split into list ['']
        if extra_repr:
            extra_lines = extra_repr.split('\n')
        child_lines = []
        for key, module in self._modules.items():
            mod_str = repr(module)
            mod_str = _addindent(mod_str, 2)
            child_lines.append('(' + key + '): ' + mod_str)
        lines = extra_lines + child_lines
    
        main_str = self._get_name() + '('
        if lines:
            # simple one-liner info, which most builtin Modules will use
            if len(extra_lines) == 1 and not child_lines:
                main_str += extra_lines[0]
            else:
                main_str += '\n  ' + '\n  '.join(lines) + '\n'
    
        main_str += ')'
        return main_str