- E04 - Leadership! Google, Guido van Rossum, PSF
Alex Martelli
aleax at mail.comcast.net
Wed Jan 4 11:02:26 EST 2006
Ilias Lazaridis <ilias at lazaridis.com> wrote:
...
> >> attr_accessor :name, :age
...
> I would need this python "attr_accessor", to showcase that python is
> capable to do it (even if the usage seems irrational/redundant).
The code for it was in one of my previous posts, in more than one form,
but here it is again, more or less:
def add_silly_attr_accessor_to_a_class(klass, name):
def get(self, name): return getattr(self, '_'+name)
def set(self, name, value): return setattr(self, '_'+name, value)
setattr(klass, name, property(get, set))
to be used as in:
add_silly_attr_accessor_to_a_class(Talker, 'name')
add_silly_attr_accessor_to_a_class(Talker, 'age')
outside of the body of Talker. If you'd rather have it used INSIDE the
body of Talker, then:
def make_silly_attr_accessor(name):
def get(self, name): return getattr(self, '_'+name)
def set(self, name, value): return setattr(self, '_'+name, value)
return property(get, set)
to be used as in:
class Talker(object):
age = make_silly_attr_accessor('age')
name = make_silly_attr_accessor('name')
Finally, you could choose to use a decorator syntax instead:
def silly_attr_accessor_via_decorator(f):
name = '_'+f.__name__
def get(self, name): return getattr(self, '_'+name)
def set(self, name, value): return setattr(self, '_'+name, value)
return property(get, set)
to be used as in:
class Talker(object):
@silly_attr_accessor_via_decorator
def name(): pass
@silly_attr_accessor_via_decorator
def age(): pass
The latter is arguably a stretching of the concept of decorator, which
is meant to be a nice syntax for a higher-order-function (taking a
function as its argument and returning another function built by
modifying the argument one) -- here we're only using the *name* of the
"function" (name or age) and ignoring the object entirely (which is why
in the example use I'm defining the ``functions'' as empty, using the
no-op statement ``pass''). Still, some people believe there is mystical
and magical power in having special syntax for something rather than
using perfectly normal, general, and existing syntax for the purpose;
such syntax-obsessed people will no doubt be more impressed by seeing
the "special syntax" in use, than by ordinary, bread-and-butter
closures, properties and assignment statements...;-)
Alex
More information about the Python-list
mailing list