python - 自定制property/property的延时计算

自定制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)
上一篇:小白学Maven第一篇配置


下一篇:Nginx+PHP(FastCGI)高性能服务器加载redis+memcache模块