Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #62486 > unrolled thread
| Started by | Devin Jeanpierre <jeanpierreda@gmail.com> |
|---|---|
| First post | 2013-12-21 04:07 -0800 |
| Last post | 2013-12-21 04:07 -0800 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: @property simultaneous setter and getter Devin Jeanpierre <jeanpierreda@gmail.com> - 2013-12-21 04:07 -0800
| From | Devin Jeanpierre <jeanpierreda@gmail.com> |
|---|---|
| Date | 2013-12-21 04:07 -0800 |
| Subject | Re: @property simultaneous setter and getter |
| Message-ID | <mailman.4466.1387627704.18130.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web