Created
January 3, 2017 08:54
-
-
Save zhu327/fc93c9182d69d10f904eb6f4f425405d to your computer and use it in GitHub Desktop.
Python class property decorator only support getattr
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 ClassPropertyDescriptor(property): | |
u""" | |
class property descriptor | |
""" | |
def __get__(self, obj, objtype=None): | |
if self.fget is None: | |
raise AttributeError("unreadable attribute") | |
return self.fget.__get__(obj, objtype)() | |
def classproperty(func): | |
if not isinstance(func, (classmethod, staticmethod)): | |
func = classmethod(func) | |
return ClassPropertyDescriptor(func) | |
class Foo(object): | |
_var = 5 | |
@classproperty | |
def var(cls): | |
return cls._var |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment