欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python-自定义property,支持缓存

程序员文章站 2022-03-03 10:26:53
...

带缓存功能的property

my_property

class my_property:
    def __init__(self, fget=None, fset=None, fdel=None, cache=False):
        self.fget = fget
        self.fset = fset
        self.fdel = fdel
        self.cache = cache

    def setter(self, func):
        if self.cache:
            raise ValueError("'setter' require cache is False")

        if self.fget is None:
            raise ValueError("descriptor 'setter' requires a 'property' object but received a 'function'")
        self.fset = func

    def deleter(self, func):
        if self.fget is None and self.fset is None:
            raise ValueError("TypeError: descriptor 'deleter' requires a 'property' object but received a 'function'")
        self.fdel = func

    def __get__(self, instance, owner):
        if instance is None:
            return self
        value = self.fget(instance)
        if self.cache:
            instance.__dict__[self.fget.__name__] = value
        return value

    def __call__(self, func):
        self.fget = func
        return self


class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

    @my_property(cache=True)
    def area(self):
        print('============计算面积啦============')
        return self.width*self.height

    @my_property
    def perimeter(self):
        print('------------计算周长啦------------')
        return (self.width + self.height) * 2


a = Rectangle(3, 4)
print(a.area)
print(a.area)

print(a.perimeter)
print(a.perimeter)

结果如下

/usr/bin/python3.6 /home/sunsong/Desktop/Demo/C.py
============计算面积啦============
12
12
------------计算周长啦------------
14
------------计算周长啦------------
14

可以看到设置缓存的没有进行第二次计算,而没有设置缓存的进行了两次计算。

相关标签: Python语言