开发者

How can I extend Image class?

I want to extend "Image" class in PIL.

#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")

RESULT: Error.myOriginal has no attribute "open".

How can I extend Image class without rewriting open() method?


According to Fredrik Lundh, the author of PIL:

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

myOriginal.py:

To delegate individual methods:

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):
        ...

Or to delegate (almost) everything to self._img, you could use __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!')

test.py:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜