Created
July 1, 2020 17:04
-
-
Save nicain/0b73eb8de959bd1f87359b0ab419f234 to your computer and use it in GitHub Desktop.
decorator that merges classmethod with property
This file contains hidden or 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 clsproperty(object): | |
"""A data descriptor that sets and returns values | |
normally and prints a message logging their access. | |
""" | |
def __init__(self, fget=None, fset=None, fdel=None, doc=None): | |
self.fget = fget | |
self.fset = fset | |
self.fdel = fdel | |
if doc is None and fget is not None: | |
doc = fget.__doc__ | |
self.__doc__ = doc | |
def __get__(self, obj, klass=None): | |
if obj is None: | |
return self | |
if self.fget is None: | |
raise AttributeError("unreadable attribute") | |
if klass is None: | |
klass = type(obj) | |
return self.fget(klass, obj) | |
def __set__(self, obj, value): | |
if self.fset is None: | |
raise AttributeError("can't set attribute") | |
self.fset(obj, value) | |
def __delete__(self, obj): | |
if self.fdel is None: | |
raise AttributeError("can't delete attribute") | |
self.fdel(obj) | |
def getter(self, fget): | |
return type(self)(fget, self.fset, self.fdel, self.__doc__) | |
def setter(self, fset): | |
return type(self)(self.fget, fset, self.fdel, self.__doc__) | |
def deleter(self, fdel): | |
return type(self)(self.fget, self.fset, fdel, self.__doc__) |
Author
nicain
commented
Jul 1, 2020
•
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment