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

代码: functools.partialmethod

from functools import partial, partialmethod

class ImageProcessor:
    def __init__(self, image_path) -> None:
        self.image_path = image_path
    def 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





代码: functools.partial

from functools import partial, partialmethod

class ImageProcessor:
    def __init__(self, image_path) -> None:
        self.image_path = image_path
    def 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, x=100, y=100, width=200, height=200)
    # small_crop = partialmethod(crop, 50, 50, 100, 100)
    # large_crop = partialmethod(crop, 200, 200, 400, 400)
    default_crop = partial(lambda self: self.crop(100, 100, 200, 200))
    small_crop = partial(lambda self: self.crop(50, 50, 100, 100))
    large_crop = partial(lambda self: self.crop(200, 200, 400, 400))

image_processor = ImageProcessor("image.jpg")
print(image_processor.default_crop)
print("-----------------")
image_processor.default_crop(image_processor)
print("-----------------")
ImageProcessor.default_crop(image_processor)
# image_processor.small_crop()
# image_processor.large_crop()




运行效果:

image



相关:

https://baijiahao.baidu.com/s?id=1842253736230956282&wfr=spider&for=pc



posted on 2025-12-13 16:55  Angry_Panda  阅读(3)  评论(0)    收藏  举报

导航