Declarative properties
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Thu Oct 11 14:42:16 EDT 2007
On Thu, 11 Oct 2007 09:58:48 -0700, Dan Stromberg wrote:
> 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:
>>
>>> 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.
It shows twice as much attributes if I inspect the objects and I don't know
which are merely useless default getters and setters. And it is more and
more complex code. Code can be cut down a bit by some metaclass magic but
this brings in another complexity.
> The "baggage" of possibly fixing (AKA "generalizing") how your attributes
> are accessed is something you lug around while your deadline looms.
Sorry I don't get it. If I want to customize the access to a "normal"
attribute I simply turn it into a property.
> 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)
And the benefit of this evil ``eval`` dance is exactly what!?
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list