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

Chris Rebert clp2 at rebertia.com
Tue May 18 16:54:30 EDT 2010


On Tue, May 18, 2010 at 1:39 PM, Vincent Davis <vincent at vincentdavis.net> 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
> 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.

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @property
    def xy(self):
        '''Will calculate x+y every time'''
        return self.x + self.y

Or if Foo is immutable and you wish to cache x+y:

class Foo(object):
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self._xy = None

    @property
    def xy(self):
        if self._xy is None:
            self._xy = self.x + self.y
        return self._xy

Suggested reading: http://docs.python.org/library/functions.html#property

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list