built-in 'property'

Alex Martelli aleaxit at yahoo.com
Wed Dec 29 04:50:54 EST 2004


Steven Bethard <steven.bethard at gmail.com> wrote:

> For this reason, I usually suggest declaring properties like[1]:
> 
> py> class E(object):
> ...     def x():
> ...         def get(self):
> ...             return float(self._x)
> ...         def set(self, x):
> ...             self._x = x**2
> ...         return dict(fget=get, fset=set)
> ...     x = property(**x())
> ...     def __init__(self, x):
> ...         self._x = x
> ...
> py> e = E(42)
> py> e.x
> 42.0
> py> e.x = 3
> py> e.x
> 9.0
> 
> Note that by using the x = property(**x()) idiom, I don't pollute my 
> class namespace with get/set/del methods that aren't really useful to
> instances of the class.  It also makes it clear to subclasses that if
> they want different behavior from the x property that they'll need to
> redefine the entire property, not just a get/set/del method.
> 
> Steve
> 
> [1] Thanks to whoever originally suggested this! Sorry, I've forgotten
> who...

In the Cookbook 2nd ed, I credited Sean Ross, the author of the CB
recipe proposing this (with credit also to David Niegard and Holger
Krekel for important comments whose contents I merged into the recipe).

Of course there are several possible variations, such as
    return locals()
instead of return dict(&c)...


Alex



More information about the Python-list mailing list