Prev: how to cause a request for a missing class attribute cause its calculation
Next: sound effects in python
From: Ethan Furman on 18 May 2010 17:19 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~
From: Ethan Furman on 18 May 2010 18:26
Ethan Furman wrote: > 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~ Chris' reply is more on-point, I think -- I was thinking of attributes that are only calculated once. *sigh* ~Ethan~ |