I tried the following code with Pytorch MSELoss class(torch.nn.MSELoss)-


the output of this was 'type'. Can you please explain to me why that is happening? Thanks in advance.


2 Answers 2


OOP in Python, pointing to advanced part of designing of class If you apply type on the name of a class itself, you get the class "type" returned (metaclass of MSELoss) and applying "type" to an object returns the class of which the object is an instance of . going back to your question: CLASS torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean')

Is a class is an instance of the class "type" and u have the expected behavior (more explanation below), don’t know what u expect to get as result. The type of MSELoss, the class itself, is type. In general, the type of any new-style class is type.

Here is a detailed explanation of metaclasses and new and Type and Class More explanation from above source:

A user-defined class (or the class "object") is an instance of the class "type". So, we can see, that classes are created from type. In Python3 there is no difference between "classes" and "types". They are in most cases used as synonyms.

The fact that classes are instances of a class "type" allows us to program metaclasses. We can create classes, which inherit from the class "type". So, a metaclass is a subclass of the class "type". Instead of only one argument, type can be called with three parameters: type(classname, superclasses, attributes_dict) If type is called with three arguments, it will return a new type object. This provides us with a dynamic form of the class statement.

  • "classname" is a string defining the class name and becomes the name attribute;
  • "superclasses" is a list or tuple with the superclasses of our class. This list or tuple will become the bases attribute;
  • the attributes_dict is a dictionary, functioning as the namespace of our class. It contains the definitions for the class body and it becomes the dict attribute.

it is because you haven't instantiated the object, add () after the name of the class

>>> from torch.nn import MSELoss
>>> type(MSELoss)
<class 'type'>
>>> type(MSELoss())
<class 'torch.nn.modules.loss.MSELoss'>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.