zoukankan      html  css  js  c++  java
  • 惰性属性

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Time    : 2019-01-23 15:05
    # @Author  : 
    # @File    : lazyproperty.py
    # @Software: Pycharm professional
    import math
    
    
    class lazyroperty:
        def __init__(self, func):
            self.func = func
    
        def __get__(self, instance, cls):
            if instance is None:
                return self
            else:
                value = self.func(instance)
                setattr(instance, self.func.__name__, value)
                return value
    
    
    class Circle:
        def __init__(self, radius):
            self.radius = radius
    
        @lazyroperty
        def area(self):
            print("computing area")
            return math.pi * self.radius ** 2
    
    
    if __name__ == '__main__':
        c = Circle(4.0)
        print(c.area)
        print(c.area)
    
    

    可以看到上面代码的输出只有一遍"computing area",惰性属性的全部意义就是用于提升程序性能,一旦访问了该属性就不会每次访问它的时候重新计算。

    Python的hasattr() getattr() setattr() 函数使用方法详解:https://www.cnblogs.com/cenyu/p/5713686.html

  • 相关阅读:
    codesmith
    moment.js
    select2
    Lodash js数据操作库
    angular.js
    vue.js
    axios.js
    RoutePrefix和Route 路由前缀
    Tuple元组 C#
    ningx访问日志切割
  • 原文地址:https://www.cnblogs.com/xLI4n/p/10309199.html
Copyright © 2011-2022 走看看