如何扩展Image类? [英] How can I extend Image class?
本文介绍了如何扩展Image类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在PIL中扩展Image类。
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")
结果:Error.myOriginal没有属性open。
RESULT: Error.myOriginal has no attribute "open".
如何在不重写open()方法的情况下扩展Image类?
How can I extend Image class without rewriting open() method?
推荐答案
作者:Fredrik Lundh ,PIL的作者:
Image类的设计不是由应用程序代码子类化的
。如果
你想要自定义行为,请使用
委托包装。
the Image class isn't designed to be subclassed by application code. if you want custom behaviour, use a delegating wrapper.
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 __
:
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()
这篇关于如何扩展Image类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文