Declarative properties

Dan Stromberg dstromberglists at gmail.com
Thu Oct 11 18:58:48 CEST 2007


On Thu, 11 Oct 2007 13:46:12 +0000, Marc 'BlackJack' Rintsch wrote:

> On Thu, 11 Oct 2007 13:04:53 +0000, Artur Siekielski wrote:
> 
>> On Oct 11, 2:27 pm, Marc 'BlackJack' Rintsch <bj_... at gmx.net> wrote:
>>> But why?  Default getters and setters are unnecessary and if you need
>>> something other than the default you need to write it anyway more
>>> explicitly.
>> 
>> I see some problems with your approach:
>> 
>> 1. If I use instance field 'name' which is accessed directly by other
>> classes,
>> and later I decide to implement nonstandard getter, I must refactor
>> 'Person' class
>> and in some places change 'name' to '_name' (assuming this is now the
>> field's name).
>> The problem is that I cannot automatically change 'name' to '_name'
>> everywhere, because
>> in some places I want public property value (eg. validated and
>> formatted), and in other
>> places raw property value.
> 
> So what?  Otherwise you carry *always* the baggage of a public property
> and a private attribute whether you need this or not.  At least for me it
> would be unnecessary in most cases.

That "baggage" of carrying around "unneeded" methods is something the
computer carries for you - IE, no big deal in 99.99% of all cases.

The "baggage" of possibly fixing (AKA "generalizing") how your attributes
are accessed is something you lug around while your deadline looms.

Here's some code that defines such methods for you:

#!/usr/bin/env python

def gimme_set_get(foo, attribute):
   lst = [ \
      'def set_%s(self, value):' % attribute, \
      '  self._%s = value' % attribute, \
      'def get_%s(self):' % attribute, \
      '  return self._%s' % attribute, \
      'foo.set_%s = set_%s' % (attribute, attribute), \
      'foo.get_%s = get_%s' % (attribute, attribute) \
      ]
   s = '\n'.join(lst)
   code = compile(s, '<string>', 'exec')
   eval(code)

class foo:
   def __init__(self, value):
      self.public_value = value
gimme_set_get(foo, 'via_accessor_method_only')

f = foo(1)
f.set_via_accessor_method_only(1/9.0)
print f.get_via_accessor_method_only()

print dir(f)





More information about the Python-list mailing list