2019年9月29日 自定制property

描述符能实现大多pyhon类特性中的底层方法,包括:classmethod  ,  staticmethd   ,   property  ,   __slots__

描述符在被修饰的类中去定义一个类属性
class Lazyproperty:
    def __init__(self,func):
        print('>>>>>',func)
        self.func=func
    def __get__(self, instance, owner):#self 是Lazyproperty()生成的对象
        print('get方法')
        return self.func(instance)#instance含义是传递的实例本身,owner是产生instance的类




class Room:
    #描述符在被修饰的类中去定义
    # area=Lazyproperty(area)#描述符操作,但是下面的@lazyproperty 就是在做相同的事情
    def __init__(self,name,width,length):
        self.name=name
        self.width=width
        self.length=length

    # @property #静态属性 有@实际就在运行 area=property(area)  相当于对property 做实例化。可以是函数,也可以是类,都能实现装饰器效果,实现了给类增加描述符area=property(area)
    @Lazyproperty
    def area(self):
        return self.width*self.length




r1=Room('cs',2,4)
print(r1.area) #此处调用的是Lazyproperty(area)后返回赋值的area,触发非数据描述符
# print(r1.area.func(r1))#纯手动触发运行

》》》》》》》》》》

get方法
8

原文地址:https://www.cnblogs.com/python1988/p/11609981.html