为什么这一行不实例化一个class?
Why does this line not instantiate a class?
我是一名 python 初学者,正在学习有关神经网络和 PY 火炬模块的教程。我不太了解这条线的行为。
import torch.nn as nn
loss = nn.MSELoss()
print(loss)
>>MSELoss()
既然nn.MSELoss是一个class,为什么调用它给变量loss而不是将它实例化为一个class对象呢? class MSELoss 中的什么类型的代码允许它实现此行为?
它确实实例化了一个 class。然而,class 实现了特殊的 __call__
方法,该方法允许您在其上使用调用运算符 ()
,就好像它是一个函数一样。它还实现了 __repr__
方法,该方法自定义打印时的显示方式。
根据Documentation,nn.MSELoss()
创建了一个衡量均方误差的标准,您可以这样使用:
loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()
您可以检查 loss
是 MSELoss
class:
print(type(loss).__name__)
>>> MSELoss
当你打印一些对象时,你实际上是在 Python 中调用它的 __str__
方法,或者如果它没有定义,那么 __repr__
(来自 表示).
你的情况是 正常 class,但 __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
我是一名 python 初学者,正在学习有关神经网络和 PY 火炬模块的教程。我不太了解这条线的行为。
import torch.nn as nn
loss = nn.MSELoss()
print(loss)
>>MSELoss()
既然nn.MSELoss是一个class,为什么调用它给变量loss而不是将它实例化为一个class对象呢? class MSELoss 中的什么类型的代码允许它实现此行为?
它确实实例化了一个 class。然而,class 实现了特殊的 __call__
方法,该方法允许您在其上使用调用运算符 ()
,就好像它是一个函数一样。它还实现了 __repr__
方法,该方法自定义打印时的显示方式。
根据Documentation,nn.MSELoss()
创建了一个衡量均方误差的标准,您可以这样使用:
loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward()
您可以检查 loss
是 MSELoss
class:
print(type(loss).__name__)
>>> MSELoss
当你打印一些对象时,你实际上是在 Python 中调用它的 __str__
方法,或者如果它没有定义,那么 __repr__
(来自 表示).
你的情况是 正常 class,但 __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