Getters and Setters

Neil Schemenauer nascheme at ucalgary.ca
Thu Jul 15 02:22:38 EDT 1999


It seems my implementation had a bug.  It did not work when the
function was stored and called multiple times.  Premature
optimization really is the root of all evil.


    Neil

======================================================================
#
# A mixin class to automagicly create getter/setter methods for
# class attributes. By default the method names are get* and
# set*. Modify as desired. Using the automatic methods seems to
# be about 10 times slower than explicit methods.
#
# Neil Schemenauer, July 1999
#

class _Getter:
    def __init__(self, value=None):
        self.value = value

    def __call__(self):
        return self.value

class _Setter:
    def __init__(self, dict=None, name=None):
        self.dict = dict
        self.name = name

    def __call__(self, value):
        self.dict.__dict__[self.name] = value
        

class GetterSetter:
    def __getattr__(self, name):
        try:
            if name[:3] == 'get':
                return _Getter(self.__dict__[name[3:]])
            elif name[:3] == 'set':
                return _Setter(self, name[3:])
        except KeyError:
            pass
        raise AttributeError


def test():
    import time
    class A(GetterSetter):
        def __init__(self):
            self.X = self.Y = 1
        def getY(self):
            return self.Y
        def setY(self, v):
            self.Y = v
    a = A()
    t = time.time()
    n = 1000
    print 'Comparing', n, 'iterations'
    for x in range(n):
        a.getX()
        a.setX(x)
    print 'GetterSetter', time.time()-t
    t = time.time()
    for x in range(n):
        a.getY()
        a.setY(x)
    print 'explicit function', time.time()-t


if __name__ == '__main__': test()




More information about the Python-list mailing list