how to cause a request for a missing class attribute cause its calculation

Ethan Furman ethan at stoneleaf.us
Tue May 18 17:19:39 EDT 2010


Vincent Davis wrote:
> Lets say I have 
> class foo(object):
>     def __init__(self, x, y):
>         self.x=x
>         self.y=y
>     def xplusy(self):
>         self.xy = x+y
                      ^ this needs to be self.x + self.y
> 
> inst = foo(1,2)
> inst.xy   # no value, but I what this to cause the calculation of inst.xy
> 
> I don't what to have self.xy calculated before it is called.

My current favorite method:

     def __getattr__(self, name):
         if name != 'xy':
             raise AttributeError("%s not found" % name)
         self.xy = self.x + self.y
         return self.xy


~Ethan~



More information about the Python-list mailing list