我在学习 PyTorch 时有一个关于 Python 语法的问题。以下代码是 PyTorch 文档中的示例。
m = nn.Linear(20, 30)
input = autograd.Variable(torch.randn(128, 20))
output = m(input)
print(output.size())
第一行是创建一个实例m
,但是为什么这个实例m
可以像第3行那样直接接收参数呢?我认为它应该使用方法来处理参数,如m.method(input)
。
最佳答案
在 python 中,任何对象都可以定义一个 __call__
方法,使其可以像您的示例中那样用作函数。
引用:https://docs.python.org/2/reference/datamodel.html#object.call
关于python - PyTorch 中未知的 Python 语法 : a instance can directly receive a parameter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48055762/