如何扩展Image类?

Yug*_*amo 6 python inheritance python-imaging-library

我想在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")
Run Code Online (Sandbox Code Playgroud)

结果:Error.myOriginal没有属性"打开".

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

unu*_*tbu 10

根据 PIL的作者Fredrik Lundh的说法:

Image类不是设计为应用程序代码的子类.如果您想要自定义行为,请使用委派包装器.

myOriginal.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):
        ...
Run Code Online (Sandbox Code Playgroud)

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

class ExtendedImage(object):
    def __init__(self,img):
        self._img=img
    def __getattr__(self,key):
        if key == '_img':
            #  http://nedbatchelder.com/blog/201010/surprising_getattr_recursion.html
            raise AttributeError()
        return getattr(self._img,key)
    def method3(self):
        print('Hiya!')
Run Code Online (Sandbox Code Playgroud)

test.py:

import Image
import myOriginal
im = myOriginal.ExtendedImage(Image.open("picture.jpg"))
im.method3()
Run Code Online (Sandbox Code Playgroud)