如何扩展Image类?

时间:2011-03-02 09:00:46

标签: 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")

结果:Error.myOriginal没有属性“open”。

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

1 个答案:

答案 0 :(得分:10)

According to Fredrik Lundh,PIL的作者:

  

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

或者将(几乎)所有内容委托给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!')

<强> test.py:

import Image
import myOriginal
im = myOriginal.ExtendedImage(Image.open("picture.jpg"))
im.method3()
相关问题