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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值