Lazy class property decorator

谁都会走 提交于 2019-12-01 22:49:03

Pyramid framework has a very nice decorator called reify, but it only works at instance level, and you want class level, so let's modify it a bit

class class_reify(object):
    def __init__(self, wrapped):
        self.wrapped = wrapped
        try:
            self.__doc__ = wrapped.__doc__
        except: # pragma: no cover
            pass

    # original sets the attributes on the instance
    # def __get__(self, inst, objtype=None):
    #    if inst is None:
    #        return self
    #    val = self.wrapped(inst)
    #    setattr(inst, self.wrapped.__name__, val)
    #    return val

    # ignore the instance, and just set them on the class
    # if called on a class, inst is None and objtype is the class
    # if called on an instance, inst is the instance, and objtype 
    # the class
    def __get__(self, inst, objtype=None):
        # ask the value from the wrapped object, giving it
        # our class
        val = self.wrapped(objtype)

        # and set the attribute directly to the class, thereby
        # avoiding the descriptor to be called multiple times
        setattr(objtype, self.wrapped.__name__, val)

        # and return the calculated value
        return val

class Test(object):
    @class_reify
    def foo(cls):
        print("foo called for class", cls)
        return 42

print(Test.foo)
print(Test.foo)

Run the program and it prints

foo called for class <class '__main__.Test'>
42
42
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!