当前位置: 首页 > news >正文

python —— 偏函数 —— functools.partial 和 functools.partialmethod

python —— 偏函数 —— functools.partial 和 functools.partialmethod

代码:

from functools import partial, partialmethodclass ImageProcessor:def __init__(self, image_path) -> None:self.image_path = image_pathdef process(self, operation, *args, **kwargs):print(f"processing image {self.image_path} 执行操作: {operation}")print(f"{args} {kwargs}")def crop(self, x, y, width, height):print(f"cropping image {self.image_path} {x} {y} {width} {height}")return self.process("crop", x=x, y=y, width=width, height=height)default_crop = partialmethod(crop, 100, 100, 200, 200)small_crop = partialmethod(crop, 50, 50, 100, 100)large_crop = partialmethod(crop, 200, 200, 400, 400)image_processor = ImageProcessor("image.jpg")
image_processor.default_crop()
image_processor.small_crop()
image_processor.large_crop()



运行效果:

image