zoukankan      html  css  js  c++  java
  • 2019年9月30日 property流程分析

    静态属性不能传参数。

    类能调用静态属性,只是返回的是一个对象。

    描述符的get方法   

    class Lazyproperty:
        def __init__(self,func):
            print('>>>>>',func)
            self.func=func
        def __get__(self, instance, owner):#self 是Lazyproperty()生成的对象
            print('get方法')
            if instance is None:
                return self #如果instance 是None,就返回Lazyproperty(area)也就是self
            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
    
        @property
        def test(self):
            return "test"
    
    
    # r1=Room('cs',2,4)
    # print(r1.area) #此处调用的是Lazyproperty(area)后返回赋值的area,触发非数据描述符
    # # print(r1.area.func(r1))#纯手动触发运行
    
    print(Room.test) #系统的property返回的是一个对象 property(test)
    print(Room.area) #因为area被代理,所以会触发描述符,无法执行self.func(instance) 用类去调用的时候,instance是None0

    》》》》》》》》》》》

    <property object at 0x03183150>
    get方法
    <__main__.Lazyproperty object at 0x03150090>

  • 相关阅读:
    运维工程师的四个阶段
    必须知道的Linux内核常识详解
    Centos7/RHEL7 开启kdump
    sort实现ip排序
    如何判断是否开启超线程
    Django---进阶12
    Django---进阶11
    前端---进阶8
    前端---进阶7
    前端---进阶6
  • 原文地址:https://www.cnblogs.com/python1988/p/11614231.html
Copyright © 2011-2022 走看看