Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #62481
| From | Peter Otten <__peter__@web.de> |
|---|---|
| Subject | Re: @property simultaneous setter and getter |
| Date | 2013-12-21 11:14 +0100 |
| Organization | None |
| References | <C1F5DCEF-67D1-410B-9900-C2866AD7882C@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.4465.1387620889.18130.python-list@python.org> (permalink) |
Brian Bruggeman wrote:
> Is this something that would be pep-able?
>
> https://gist.github.com/brianbruggeman/8061774
There's no need to put such a small piece of code into an external
repository.
> class someAwesomeClass(object):
> """ an example """
>
> @property
> def some_attr(self, value=None):
> """
> Implementation of a setter and getter property in one
> """
> attr = "__local_attr__"
> if not hasattr(self, attr):
> setattr(self, attr, value)
> if (value != None and hasattr(self, attr)):
> setattr(self, attr, value)
> return getattr(self, attr)
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...
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: @property simultaneous setter and getter Peter Otten <__peter__@web.de> - 2013-12-21 11:14 +0100
csiph-web