[Tutor] Passing attribute calls to has-a classes

Joel Ricker joel@prettyhipprogramming.com
Sat Feb 8 17:10:04 2003


Hi all,

[Python 2.1]

I've been working with the PIL package and ran into a little snag.  I
wanted to extend their Image type but unfortunately, they use a factory
to build the object up. I wasn't sure quite sure I could extend this as
is so I just wrapped my own class around it.

What I would like to do is take any property calls and send them on to
the wrapped object, intercepting the ones I need for the class.  My
problem is I keep getting in an infinite loop when I do.

My code snippet:

class MyImage:

	def __init__(self, fp):
		self.master = Image.open(fp)

	def __getattr__(self, name):
		return self.master.__getattr__(name)
		#I've also tried getattr(self.master, name)

	def __setattr__(self, name, value):
		self.master.__setattr__(name, value)
		#I've also tried setattr(self.master, name, value)

Also, how can I catch calls to methods so that I can pass them on to the
object self.master or is this even possible?

ie, 

my = MyImage("image.jpg")
my.show()
# Since MyImage doesn't have a show() method, I'd like to catch that and
try sending in to
# self.master and if that still doesn't work, throw an error.

Thanks
Joel