PEP318: property as decoration

Sean Ross frobozz_electric at hotmail.com
Wed Jun 11 11:37:19 EDT 2003


"Sean Ross" <sross at connectmail.carleton.ca> wrote in message
news:DIuFa.5725$Gm4.690616 at news20.bellglobal.com...
>  def propertythunk():
>       def fget(self):
>            return self._foo
>       def fset(self, value):
>            self._foo = value
>       def fdel(self):
>            del self._foo
>       fdoc = "foo"
>       return fget, fset, fdel, fdoc



After thinking about this for a bit I realized that you could do the
following to define properties:

class MyClass(object):
        def __init__(self):
                self._foo = "foo"
                self._bar = "bar"

        def foo():
                def fget(self):
                        return self._foo
                def fset(self, value):
                        self._foo = value
                def fdel(self):
                        del self._foo
                fdoc = "foo"
                return fget, fset, fdel, fdoc
        foo = property(*foo())

        def bar():
                "a readonly property"
                def fget(self):
                        return self._bar
                return fget,     # the trailing comma is required here
        bar = property(*bar())

x = MyClass()
print x.foo
x.foo = "changed"
print x.foo
print x.bar


This may seem obvious, but it hadn't occured to me before. Using this
approach addresses the concern I raised regarding the cluttering of the
class scope with expendable methods, e.g., getfoo, setfoo, delfoo. Now,
there is only foo, which is very nice.

For bar, which only defines a get method, this approach seems excessive -
why not just make getbar and be done with it? You could. I just like the
fact that after I've made my bar property, there are no superfluous method
lying around inside MyClass.

Anyway...I found this interesting, so I thought someone else might enjoy it
as well.







More information about the Python-list mailing list