[Tutor] Class Attribute "Overloading?"
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 16 01:28:30 CEST 2007
"Vincent Gulinao" <vincent.gulinao at gmail.com> wrote in message
news:fcc3e6170708151159lf302c3er636eabb627606f23 at mail.gmail.com...
> Sorry about that. I want something like:
>
> class foo:
>
> def __init__(self):
> self.attr1 = None
> def get_attr1(self):
> if not self.attr1:
> attr1 = <get value from DB, very expensive query>
> self.attr1 = attr1
> return self.attr1
>
> such that:
> foo_instance = foo()
> foo_instance.get_attr1()
> foo_instance.attr1
>
> gets the same value.
That looks like an ideal candidate for a "property".
Using a property you can treat it as a data item but behind
the scenes call a getter and setter method. In your case the
getter would be the method you have above and the setter
could write the new value to the database, if needed.
Thus after defining the property attr1 you access like:
foo_instance = Foo()
print foo.attr1 # executes the getter
foo.attr1 = 42 # executes the setter
HTH,
--
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list