如何扩展图像类?

2024-10-01 00:16:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在PIL中扩展“Image”类。在

#module Image
def open(file): ...
class Image:
    def method1:...
    def method2:...

#module myOriginal
from Image import Image
class ExtendedImage(Image):
    def method3:...

#module test
import myOriginal
im = myOriginal.open("picture.jpg")

结果:错误.myOriginal没有“打开”属性。在

如何在不重写open()方法的情况下扩展Image类?在


Tags: fromtestimageimportpildefopenclass
1条回答
网友
1楼 · 发布于 2024-10-01 00:16:42

According to Fredrik Lundh,PIL的作者:

the Image class isn't designed to be subclassed by application code. if you want custom behaviour, use a delegating wrapper.

肌原创性.py

委派个别方法:

class ExtendedImage(object):
    def __init__(self,img):
        self._img=img
    def method1(self):
        return self._img.method1()    #<  ExtendedImage delegates to self._img
    def method3(self):
        ...

或者要(几乎)将所有内容委托给self._img,可以使用__getattr__

^{pr2}$

测试.py:

import Image
import myOriginal
im = myOriginal.ExtendedImage(Image.open("picture.jpg"))
im.method3()

相关问题 更多 >