Getters and Setters

Gordon McMillan gmcm at hypernet.com
Thu Jul 15 12:21:54 EDT 1999


Neil Schemenauer writes:
> >[Neil Schemenauer]
> >> Recently I found myself wishing that Python had automatic getters
> >> and setters like CLOS.
[Tim]
> >Bleech.
[Neil]
> Bleech to CLOS or to Lisp or to automatic getters and setters?

I vote for the last. Note that Python is in the unusual position that 
it's easier to fool a class user into thinking he's doing a straight 
attribute access (while in fact being shunted through methods) than 
the other way 'round.

[code contest]
> Your code is fast and elegant but it causes reference loops.  If
> only Python had real GC (and closures and macros and generators and
> coroutines and ...).

Without bothering with petty details like timing, I claim moral 
victory <wink> based on the following:
----------------------------------------------------------
from types import FunctionType

class GetSetMeta:
    def __init__(self, name, bases, nmspace):
        self._name, self._bases, self._nmspace = name, bases, nmspace
    def __call__(self, *args):
        return GetSetHelper(self, args)

class GetSetHelper:
    def __init__(self, klass, args):
        self.__class__.__name__ = klass._name
        for (k,v) in klass._nmspace.items():
            self.__class__.__dict__[k] = v
            if not type(v) is FunctionType:
                def getter(self, nm=k):
                    return getattr(self, nm)
                def setter(self, value, nm=k):
                    setattr(self, nm, value)
                self.__class__.__dict__['get%s'%k] = getter
                self.__class__.__dict__['set%s'%k] = setter
        init = self.__class__.__dict__.get('__init__', None)
        if init:
            apply(init, (self,) + args)

MC = GetSetMeta('GetSetMeta', (), {})

class A(MC):
    foo = 1
    def __init__(self):
        bar = 2

a = A()

print `a.getfoo()`
a.setfoo(3)
print `a.getfoo()`
try:
    print `a.getbar()`
except AttributeError:
    print 'Only attributes with class level defaults acquire get/set
    methods'

-----------------------------------------------

Timings, complaints and further one-upmanships > dev/null


- Gordon




More information about the Python-list mailing list