Declarative properties
Bruno Desthuilliers
bdesth.quelquechose at free.quelquepart.fr
Mon Oct 8 08:04:49 EDT 2007
Dan Stromberg a écrit :
(snip)
> My implementation may or may not be lacking (feel free to improve it - in
> fact, please do!),
Since you ask for it:
def makeprop(name):
_name = '_' + name
def fget(self):
return getattr(self, _name, None)
def fset(self, val):
setattr(self, _name, val)
return property(fget, fset)
class AutoPropType(type):
def __init__(cls, clsname, bases, attribs):
for name in cls._autoprops:
if name not in attribs:
setattr(cls, name, makeprop(name))
class Demo(object):
__metaclass__ = AutoPropType
_autoprops = ('foo', 'bar', 'baaz')
def __init__(self, foo, bar=42, baaz='ni'):
self.foo = foo
self.bar = bar
self.baaz = baaz
d = Demo('yadda yadda')
> but that's irrelevant to the heart of the matter, which
> is "what you didn't think to plan for now most definitely can hurt you
> later".
Ahem... Please let me know, Mr Professor, what difference it would make,
from client code's POV, if we simply wrote this instead:
class Demo(object):
def __init__(self, foo, bar=42, baaz='ni'):
self.foo = foo
self.bar = bar
self.baaz = baaz
(snip more blah)
> Little hackish tricks for performance's sake scattered throughout a
> program are very wasteful of something more precious than CPU time.
Indeed. The point you're missing is that, in a language that supports
computed attributes, using plain attributes when that's all you need is
*not* a 'litlle hackish trick'. It's just common sense - and actually
saves on *both* programmer's and CPU time.
More information about the Python-list
mailing list