[英]What gets printed when you print a object of some class in python?
I want to ask about this specific example, taken from the official pytorch tutorial .我想问一下这个具体的例子,取自官方的pytorch教程。
import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
# 1 input image channel, 6 output channels, 3x3 square convolution
# kernel
self.conv1 = nn.Conv2d(1, 6, 3)
self.conv2 = nn.Conv2d(6, 16, 3)
# an affine operation: y = Wx + b
self.fc1 = nn.Linear(16 * 6 * 6, 120) # 6*6 from image dimension
self.fc2 = nn.Linear(120, 84)
self.fc3 = nn.Linear(84, 10)
net = Net()
print(net)
And the output is输出是
Net(
(conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))
(conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))
(fc1): Linear(in_features=576, out_features=120, bias=True)
(fc2): Linear(in_features=120, out_features=84, bias=True)
(fc3): Linear(in_features=84, out_features=10, bias=True)
)
As I understand, this code defines a child class Net
of nn.Module
, and defines in its initializer the members conv1
, conv2
, etc. These members are printed when print(net)
is called.据我了解,这段代码定义了
nn.Module
的子类Net
,并在其初始值设定项中定义了成员conv1
、 conv2
等。这些成员在调用print(net)
时print(net)
。 Based on this obsevation, I thought that if I add the line self.x = 0
to the initializer of Net
, there would be an extra line of output, something like: (x): 0
.基于这种观察,我认为如果将
self.x = 0
行添加到Net
的初始值设定项中,则会有额外的输出行,例如: (x): 0
。 But that didn't happen.但这并没有发生。 So who decides which part of
Net
gets printed?那么谁来决定打印
Net
哪一部分呢?
From the Python3 documentation来自Python3 文档
repr(object)
代表(对象)
Return a string containing a printable representation of an object.返回一个包含对象的可打印表示的字符串。 For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object.
对于许多类型,此函数会尝试返回一个字符串,该字符串在传递给 eval() 时将产生具有相同值的对象,否则表示为包含在尖括号中的字符串,其中包含对象类型的名称附加信息通常包括对象的名称和地址。 A class can control what this function returns for its instances by defining a __repr__() method.
类可以通过定义 __repr__() 方法来控制此函数为其实例返回的内容。
Since your class inherits the nn.Module class, it uses its repr method由于您的类继承了 nn.Module 类,因此它使用其repr 方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.