Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #62486

Re: @property simultaneous setter and getter

References <C1F5DCEF-67D1-410B-9900-C2866AD7882C@gmail.com> <l93pm0$u3u$1@ger.gmane.org>
From Devin Jeanpierre <jeanpierreda@gmail.com>
Date 2013-12-21 04:07 -0800
Subject Re: @property simultaneous setter and getter
Newsgroups comp.lang.python
Message-ID <mailman.4466.1387627704.18130.python-list@python.org> (permalink)

Show all headers | View raw


On Sat, Dec 21, 2013 at 2:14 AM, Peter Otten <__peter__@web.de> wrote:
> If I were to implement something like this I'd probably use the old trick
> with nested functions:
>
> def getset(f):
>     funcs = f()
>     return property(funcs.get("get"), funcs.get("set"))
>
> class A(object):
>     @getset
>     def attr():
>         def get(self):
>             print("accessing attr")
>             return self._attr
>         def set(self, value):
>             print("setting attr to {}".format(value))
>             self._attr = value
>         return locals()
>
> if __name__ == "__main__":
>     a = A()
>     a.attr = 42
>     print(a.attr)
>
> This has been around awhile, but I don't see widespread adoption...

IMO: Because classes are the normal way of grouping functions together
in Python.

In fact, we already have an interface for these classes: the
descriptor protocol. Unfortunately it's pretty annoying to define
"properties" directly using the descriptor protocol, because its
__get__ is weird and difficult to remember how to make work correctly.
Also because the decorator making this convenient has been vanished in
python 3. ;)

class A(object):
    _attr = None

    @apply
    class attr(object):
        def __get__(self, instance, owner):
            if instance is None:
                return self

            print "accessing attr"
            return instance._attr

        def __set__(self, instance, value):
            print "setting attr to {}".format(value)
            instance._attr = value

a = A()
a.attr
a.attr = 42


A().attr
A().attr = 3

-- Devin

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: @property simultaneous setter and getter Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-12-21 04:07 -0800

csiph-web