classproperty.py 804 B

1234567891011121314151617181920212223242526272829
  1. class ClassPropertyDescriptor(object):
  2. def __init__(self, fget, fset=None):
  3. self.fget = fget
  4. self.fset = fset
  5. def __get__(self, obj, klass=None):
  6. if klass is None:
  7. klass = type(obj)
  8. return self.fget.__get__(obj, klass)()
  9. def __set__(self, obj, value):
  10. if not self.fset:
  11. raise AttributeError("can't set attribute")
  12. type_ = type(obj)
  13. return self.fset.__get__(obj, type_)(value)
  14. def setter(self, func):
  15. if not isinstance(func, (classmethod, staticmethod)):
  16. func = classmethod(func)
  17. self.fset = func
  18. return self
  19. def classproperty(func):
  20. if not isinstance(func, (classmethod, staticmethod)):
  21. func = classmethod(func)
  22. return ClassPropertyDescriptor(func)