property() usage - is this as good as it gets?

Medardo Rodriguez med.swl at gmail.com
Fri Aug 22 16:11:54 EDT 2008


On Fri, Aug 22, 2008 at 1:49 PM, Miles <semanticist at gmail.com> wrote:
> from operator import attrgetter
> class attrsetter(object):
>    def __init__(self, attr):
>        self._attr = attr
>    def __call__(self, object, value):
>        setattr(object, self._attr, value)

This solution is very nice, but in programming is a good practice to be uniform:
The interface of "attrgetter" is "def attrgetter(*names): ..."
So, it will be nice the same for attrsetter: "def attrsetter(*names):"

I will send an example, but extending it a little bit and also using
some nice python structures of functional programming:

#<code>
from operator import attrgetter

def attrsetter(*names):
    def closure(obj, *values):
        for i in xrange(len(names)):
            setattr(obj, names[i], values[i])
    return closure

attrmanager = lambda name: (attrgetter(name), attrsetter(name))


class Test(object):
    x = property(*attrmanager('_x'))
    y = property(*attrmanager('_y'))

    setvalues = attrsetter('x', 'y')


test = Test()

test.x = 1
print 'test.x:', test.x

test.y = 'Merchise'
print 'test.y:', test.y


# Just another test

test.setvalues(3, 'med')

print 'test.x:', test.x
print 'test.y:', test.y
#</code>

Regards



More information about the Python-list mailing list