Declarative properties
George Sakkis
george.sakkis at gmail.com
Thu Oct 11 19:04:27 EDT 2007
On Oct 11, 7:48 am, Artur Siekielski <artur.siekiel... at gmail.com>
wrote:
> I know about 'property' function in Python, but it's normal usage
> isn't declarative, because I have to code imperatively getters and
> setters:
>
> class Person(object):
> def __init__(self, name):
> self._name = name
> def _get_name(self):
> return self._name
> def _set_name(self, new_name):
> self._name = new_name
> name = property(_get_name, _set_name)
>
> I would like to have something like that:
>
> class Person(object):
> name = property('_name')
By now you must have been convinced that default getters/setters is
not a very useful idea in Python but this does not mean you can't do
it; it's actually straightforward:
def make_property(attr):
return property(lambda self: getattr(self,attr),
lambda self, value: setattr(self, attr, value))
class Person(object):
name = make_property('_name')
def __init__(self, name):
self.name = name
You could take it even further by removing the need to repeat the
attribute's name twice. Currently this can done only through
metaclasses but in the future a class decorator would be even better:
def PropertyMaker(*names, **kwds):
format = kwds.get('format', '_%s')
def meta(cls,bases,attrdict):
for name in names:
attrdict[name] = make_property(format % name)
return type(cls,bases,attrdict)
return meta
class Person(object):
__metaclass__ = PropertyMaker('name', format='__%s__')
def __init__(self, name):
self.name = name
print self.__name__
George
More information about the Python-list
mailing list