类方法@classmethod的作用
这段代码中用到了@classmethod,下面就总结一下@classmethod的用法,以及为什么会用到@classmethod
class Net(nn.Module):
def __init(self,arg1,arg2,...):
...
def forward(self,x):
...
return x
@classmethod
def build(cls,...):
...
net = cls(arg1,arg2,...)
return net
model = Net.build(...)
1)@classmethod定义出来的函数能够在类对象实例化之前调用这些函数
有的时候在实例化之前,就需要先和类做一定的交互,比如Net类的实例化其实是通过调用build()函数完成的
net = cls(arg1,arg2,...)
2)某个函数前面加上了staticmethod或者classmethod的话,那么这个函数就可以不通过实例化直接调用
3)类方法的第一个参数(cls)指代的就是类本身。类方法会用这个类来创建并返回最终的实例
build()函数中的cls指代的是Net类,用来之后的实例化
net = cls(arg1,arg2,...)
return net
这里return出去的net就是实例化好的Net对象