首页 > 编程语言 > 详细

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

时间:2018-10-18 10:27:51      阅读:128      评论:0      收藏:0      [点我收藏+]

自定制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的延时计算

原文:https://www.cnblogs.com/Anec/p/9799693.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!