Using property() on classmethods

后端 未结 15 758
Happy的楠姐
Happy的楠姐 2020-11-22 16:55

I have a class with two class methods (using the classmethod() function) for getting and setting what is essentially a static variable. I tried to use the property() functi

15条回答
  •  感情败类
    2020-11-22 17:42

    Here is my solution that also caches the class property

    class class_property(object):
        # this caches the result of the function call for fn with cls input
        # use this as a decorator on function methods that you want converted
        # into cached properties
    
        def __init__(self, fn):
            self._fn_name = fn.__name__
            if not isinstance(fn, (classmethod, staticmethod)):
                fn = classmethod(fn)
            self._fn = fn
    
        def __get__(self, obj, cls=None):
            if cls is None:
                cls = type(obj)
            if (
                self._fn_name in vars(cls) and
                type(vars(cls)[self._fn_name]).__name__ != "class_property"
            ):
                return vars(cls)[self._fn_name]
            else:
                value = self._fn.__get__(obj, cls)()
                setattr(cls, self._fn_name, value)
                return value
    

提交回复
热议问题