python: __call__方法
可调用对象:
自定义的函数、内置函数和类都属于可调用对象,但凡是可以把一对括号() 应用到某个对象身上都可称之为可调用对象,判断对象是否为可调用对象可以用函数 callable。
类中的__call__方法:
__call__方法让类的实例的行为表现的像函数一样,允许一个类的实例像函数一样被调用。实质上说,这意味着 x() 与 x. __ call __ () 是相同的。注意 __ call __ 参数可变。这意味着你可以定义 __ call __ 为其他你想要的函数,无论有多少个参数。
class Entity:
'''调用实体来改变实体的位置。'''
def __init__(self, size, x, y):
self.x, self.y = x, y
self.size = size
def __call__(self, x, y):
'''改变实体的位置'''
self.x, self.y = x, y
e = Entity(1, 2, 3) // 创建实例
e(4, 5) //实例可以像函数那样执行,并传入x y值,修改对象的x y
pytorch 在对图象进行transforms时就用到了__ call __ 方法, 这样对每一幅图象进行处理时就没必要每次都传入转化参数,只需要初始化实例一次即可。
class Rescale(object):
"""Rescale the image in a sample to a given size.
Args:
output_size (tuple or int): Desired output size. If tuple, output is
matched to output_size. If int, smaller of image edges is matched
to output_size keeping aspect ratio the same.
"""
def __init__(self, output_size):
assert isinstance(output_size, (int, tuple))
self.output_size = output_size
def __call__(self, sample):
image, landmarks = sample['image'], sample['landmarks']
h, w = image.shape[:2]
if isinstance(self.output_size, int):
if h > w:
new_h, new_w = self.output_size * h / w, self.output_size
else:
new_h, new_w = self.output_size, self.output_size * w / h
else:
new_h, new_w = self.output_size
new_h, new_w = int(new_h), int(new_w)
img = transform.resize(image, (new_h, new_w))
# h and w are swapped for landmarks because for images,
# x and y axes are axis 1 and 0 respectively
landmarks = landmarks * [new_w / w, new_h / h]
return {'image': img, 'landmarks': landmarks}
只需要对每幅图像调用__ call __函数即可:
tsfm = Transform(params)
transformed_sample = tsfm(sample)