zoukankan      html  css  js  c++  java
  • 2019年10月1日 实现延迟计算功能

    class Lazyproperty:
        def __init__(self,func):
            print('>>>>>',func)
            self.func=func
        def __get__(self, instance, owner):#self 是Lazyproperty()生成的对象
            print('get方法')
            if instance is None:
                return self #如果instance 是None,就返回Lazyproperty(area)也就是self
            res=self.func(instance)#instance含义是传递的实例本身,owner是产生instance的类
            setattr(instance,self.func.__name__,res) #将res结果放入instance实例字典中,实现延迟计算,而且不能有set,不然会成为数据描述符,优先级高于实例属性
            return res
    
    
    
    
    class Room:
        #描述符在被修饰的类中去定义
        # area=Lazyproperty(area)#描述符操作,但是下面的@lazyproperty 就是在做相同的事情
        def __init__(self,name,width,length):
            self.name=name
            self.width=width
            self.length=length
    
        
        @Lazyproperty
        def area(self):
            return self.width*self.length
    
    
    r1=Room('cs',12,34)
    print(r1.area)
    print(r1.__dict__)

    》》》》》

    get方法
    408
    {'name': 'cs', 'width': 12, 'length': 34, 'area': 408}

  • 相关阅读:
    JS 面向对象
    inline-block元素间隙处理
    MUI
    MUI
    chrome://inspect调试html页面空白,DOM无法加载的解决方案
    MUI
    MUI
    MUI
    MUI
    MUI
  • 原文地址:https://www.cnblogs.com/python1988/p/11616213.html
Copyright © 2011-2022 走看看