how to cause a request for a missing class attribute cause its calculation
Ethan Furman
ethan at stoneleaf.us
Tue May 18 18:26:57 EDT 2010
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~
More information about the Python-list
mailing list