[Tutor] Passing attribute calls to has-a classes

Jeff Shannon jeff@ccvcorp.com
Mon Feb 10 15:00:43 2003


Joel Ricker wrote:

>Aha, figured it out!
>
>: My code snippet:
>: 
>: class MyImage:
>: 
>: 	def __init__(self, fp):
>: 		self.master = Image.open(fp)
>
>My problem was here, I needed to say:
>
>		self.__dict__['master'] = Image.open(fp)
> 
>: 	def __getattr__(self, name):
>: 		return self.master.__getattr__(name)
>: 		#I've also tried getattr(self.master, name)
>
>and:
>		return getattr(self.master, name)
> 
>: 	def __setattr__(self, name, value):
>: 		self.master.__setattr__(name, value)
>: 		#I've also tried setattr(self.master, name, value)
>
>and:
>		return setattr(self.master, name, value)
>  
>

I would've thought that anywhere in these methods where you're using 
self.master, you would want to change it to use self.__dict__['master'] 
-- by using self.master in __getattr__(), you're setting up a 
potentially infinite loop of recursive __getattr__() calls.  

[...]
    def __getattr__(self, name):
        return getattr(self.__dict__['master'], name)
    def __setattr__(self, name, value):
        return setattr(self.__dict__['master'], name, value)

I suppose that the change wouldn't be necessary in __setattr__(), 
because the 'self.master' resolution would pass through your 
__getattr__() which should return the right object (though using the 
instance dict directly cuts out an unneeded layer of indirection), but 
I'd be very surprised if your class actually works with 'self.master' 
used in __getattr__().

Jeff Shannon
Technician/Programmer
Credit International