[Python-Dev] Definining properties - a use case for class decorators?
murman at gmail.com
Mon Oct 17 09:09:12 CEST 2005
On 10/16/05, Nick Coghlan <ncoghlan at iinet.net.au> wrote:
> On and off, I've been looking for an elegant way to handle properties using
Why use decorators when a metaclass will already do the trick, and
save you a line? This doesn't necessarily get around Antoine's
complaint that it looks like self refers to the wrong type, but I'm
not convinced anyone would be confused.
def __new__(cls, name, bases, dct):
if bases is object: # allow us to create class Property
return type.__new__(cls, name, bases, dct)
return property(dct.get('get'), dct.get('set'),
def __init__(cls, name, bases, dct):
if bases is object:
return type.__init__(cls, name, bases, dct)
__metaclass__ = MetaProperty
"""The foo property"""
def get(self): return self._foo
def set(self, val): self._foo = val
def delete(self): del self._foo
test = Test()
test.foo = 'Yay!'
assert test._foo == 'Yay!'
More information about the Python-Dev