Python中的object.method()与method(object)

在包括但不限于pytorch的许多函数中

可以有object.method()与method(object)两种写法。

例如

x = torch.Tensor([[1,2,3,4]])
x.squeeze(0)
torch.squeeze(x, 0)

我们做试验:
一。
import torch
x = torch.Tensor([[1,2,3,4]])
print(x)
print(x.squeeze(0))
print(x)

结果:

tensor([[1., 2., 3., 4.]])
tensor([1., 2., 3., 4.])
tensor([[1., 2., 3., 4.]])

可见object.method()不改变object的内部数据

二。

import torch
x = torch.Tensor([[1,2,3,4]])
print(x)
print(torch.squeeze(x, 0))
print(x)

结果:

tensor([[1., 2., 3., 4.]])
tensor([1., 2., 3., 4.])
tensor([[1., 2., 3., 4.]])

可见method(object)也不改变object的内部数据

这么说两种写法等价?是object.method()用起来更方便,但有时候可能代码提示不是很好。

有待进一步探究后更新。

原文地址:https://www.cnblogs.com/gagaein/p/13941442.html