Properties vs. get/set-methods

Denis S. Otkidach ods at fep.ru
Fri Aug 23 12:02:37 CEST 2002


On 22 Aug 2002, Aahz wrote:

A> >So far I guess this would have a performance drawback and a
A> loss
A> >of clarity here just in favour of having the possibility to
A> do
A> >instance.attribute = value instead of
A> instance.setAttribute(value).
A> >Seems to me that this really is not the scenario properties
A> were
A> >invented for!?  What am I missing here?
A>
A> You're missing that it's exactly the scenario properties are
A> for.  ;-)

One more real example for very fast caching attribute access:

class CachedAttribute(object):

    def __init__(self, method, name=None):
        self.method = method
        self.name = name or method.__name__

    def __get__(self, inst, cls):
        result = self.method(inst)
        setattr(inst, self.name, result)
        return result


class MyClass(object):

    def myAttr(self):
        ...
        return result
    myAttr = CachedAttribute(myAttr)

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]
http://diveinto.python.ru/ [ru]





More information about the Python-list mailing list