Declarative properties
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Oct 12 03:42:28 EDT 2007
Dan Stromberg a écrit :
> 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.
1/ Accessing the value of a property is not free. Accessing a plain
attribute is much cheaper.
2/ cluttering the class's namespace with useless names and the source
code with useless code is definitively not a good thing.
> 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)
Yuck. This is not only a waste of time, but also badly coded. have mercy
and at least learn how to properly use lexical scoping and closures.
> 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)
>
Correction: this is not only a waste of time and badly coded, this is
also misleading and braindead.
More information about the Python-list
mailing list