Declarative properties

Bruno Desthuilliers bruno.42.desthuilliers at wtf.websiteburo.oops.com
Thu Oct 11 12:58:44 EDT 2007


Artur Siekielski a écrit :
> 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).

Why so ?

class Toto(object):
   def __iinit__(self, name):
     self.name = name
   @apply
   def name():
     def fget(self):
       print "getting %s.name" % self
       return self._name
     def fset(self, val):
       print "setting %s.name to %s" % (self, val)
       self._name = name
   def say_hello(self):
     print "Hello, my name is %s" % self.name

t = Toto('bruno')
t.say_hello()

> 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.

But then, you do know where you want the raw value, don't you ? And this 
  would be for special cases that didn't exist before this refactoring, 
anyway ?

> 2. Properties define (a part of) public interface of a class.

So do attributes.

> When
> using fields for public
> access, you must tell this explicitly in documentation, or use name
> convention. And public
> fields definition is mixed with private fields, which doesn't happen
> when using properties.

I just don't understand what you're saying here. As long as you did not 
prefix a name with an underscore, it's part of the API. And anyway, 
nothing (except common sens) will prevent anyone to mess with 
implementation attributes.

> 3. Using properties as first-class objects

Which they are already - I don't know of anything that isn't a 
"first-class" object in Python.




More information about the Python-list mailing list