1. 程式人生 > >python - 自定制property/property的延時計算

python - 自定制property/property的延時計算

div bsp 實例 取數 int python color urn 二次

自定制prooerty:

#模擬@property 實現將類的函數屬性變成類屬性:

#定義描述符
class msf():
    def __init__(self,obj):
        self.obj = obj

    def __get__(self, instance, owner):
        if instance is None:
            return self
        re = self.obj(instance)
        instance.__dict__[self.obj.__name__] = re
        return
re class Test(): def __init__(self,x,y): self.x = x self.y = y @msf # @property def area(self): area = self.x*self.y return area a = Test(43856,2986) print(a.area) print(Test.area) print(a.__dict__) #第二次訪問屬性,就沒有觸發get方法,直接在實例屬性中提取數據 print(a.area)

python - 自定制property/property的延時計算