Created
December 19, 2012 21:38
-
-
Save lqc/4340763 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PropertyMeta(type): | |
def __new__(metaclass, name, bases, body): | |
if bases == (object,): | |
return super(PropertyMeta, metaclass).__new__(metaclass, name, bases, body) | |
return property(**{k.strip("__"): v for k, v in body.iteritems() if k in ("fget", "fset", "fdel", "__doc__")}) | |
class xproperty(object): | |
__metaclass__ = PropertyMeta | |
class Foo(object): | |
def __init__(self): | |
self._foo = 42 | |
class foo(xproperty): | |
"""The foo property.""" | |
def fget(self): | |
return self._foo | |
def fset(self, value): | |
self._foo = value | |
def fdel(self): | |
del self._foo | |
x = Foo() | |
print x.foo | |
x.foo = 13 | |
print x._foo | |
del x.foo | |
print hasattr(x, "_foo") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice, but why a metaclass, not a decorator?
Seems simpler this way, are there any downsides I'm missing?