让python类直接被调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_19332527/article/details/83077199

之前在pytorch和keras中经常发现一个类model被直接调用,发现很有意思。于是就去看了看pytorch中nn.Module的源码,发现是定义了__call__(self)函数再去调用forward()函数。举个例子如下: 

import math
class Pow(object):
	def __init__(self,n=2):
		self.n=n
		super(Pow,self).__init__()
	def forward(self,x):
		return math.pow(x,self.n)
	def __call__(self,x):
		return self.forward(x)
l=Pow(2)
y=l(10)
print(y)  #输出结果是100
l=Pow(3)
y=l(10)
print(y)  #输出结果是1000

猜你喜欢

转载自blog.csdn.net/qq_19332527/article/details/83077199
今日推荐