[prev in list] [next in list] [prev in thread] [next in thread]
List: python-list
Subject: Re: built-in 'property'
From: aleaxit () yahoo ! com (Alex Martelli)
Date: 2004-12-29 9:50:54
Message-ID: 1gpjvw8.17nwj0q1eul1qeN%aleaxit () yahoo ! com
[Download RAW message or body]
Steven Bethard <steven.bethard@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
--
http://mail.python.org/mailman/listinfo/python-list
[prev in list] [next in list] [prev in thread] [next in thread]
Configure |
About |
News |
Add a list |
Sponsored by KoreLogic