python custom property

class Pro:
     DEF  __init__ (Self, FUNC): 
        self.func = FUNC 

    DEF  __get__ (Self, instance, owner):
         return self.func (instance) 



class Room:
     DEF  __init__ (Self, name, width, length): 
        Self. name = name 
        self.width = width 
        self.length = length 

    @Pro # area = Pro (area) by the non-data descriptors Pro, so here is equivalent to the area made the attribute class descriptor, area.func = this function area 
    DEF area (Self):
         return self.width * self.length

r1 = Room ( ' alex ' , 12,2 )
 Print (r1.area)   # execution r1.area, will trigger the get method Pro descriptor, get the method of execution is a method that area passed in this instance is r1 objects

 

Guess you like

Origin www.cnblogs.com/xieys-1993/p/11593484.html