October 1, 2019 to achieve delay calculation function

class Lazyproperty:
     DEF  the __init__ (Self, FUNC):
         Print ( ' >>>>> ' , FUNC) 
        self.func = FUNC
     DEF  __get__ (Self, instance, owner): # Self is Lazyproperty () generated object 
        Print ( ' get method ' )
         IF instance iS None:
             return Self # If the instance is None, returns Lazyproperty (area) i.e. Self 
        RES = self.func (instance) # instance meaning examples of delivery itself, owner class instance is generated
        setattr (. instance, self.func the __name__ , res) # The result res instance into the dictionary example, to achieve a delay calculation, and SET can not have, or will become a data descriptor, a higher priority than the instance attribute 
        return res 




class Room:
     # descriptor is modified to define the class 
    # Area = Lazyproperty (Area) # descriptor operation, but the following is @lazyproperty do the same thing in 
    DEF  the __init__ (Self, name, width, length): 
        the 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}

Guess you like

Origin www.cnblogs.com/python1988/p/11616213.html