• 利用描述符自定制property


    property 即静态方法

    class Lazyproperty:
        def __init__(self,func):
            self.func = func
        def __get__(self, instance, owner):
            print('正在执行get方法')
            if instance is None:
                return self
            res = self.func(instance)
            return res
    
    class Room:
        def __init__(self,name,width,length):
            self.name = name
            self.width = width
            self.length = length
        @Lazyproperty  #area = Lazyproperty(area)
        def area(self):
            return self.width * self.length
        @property   #自带的property方法
        def area1(self):
            return self.width * self.length
    
    
    r1 = Room('jinling',10,10)
    print(r1.area)
    print(Room.area1)
    print(Room.area)
    

    property补充

    class Foo:
        @property
        def AAA(self):
            print('get的时候运行')
        @AAA.setter
        def AAA(self,val):
            print('set的时候运行我啊',val)
        @AAA.deleter
        def AAA(self):
            print('del的时候运行我啊')
    
    #只有在属性AAA定义property后才能定义AAA.setter, AAA.delete
    f1 = Foo()
    f1.AAA
    f1.AAA = 'jinling'
    del f1.AAA
    

     

    另一种用法

    class Foo:
    
        def get_AAA(self):
            print('get的时候运行')
    
        def set_AAA(self,val):
            print('set的时候运行我啊',val)
    
        def del_AAA(self):
            print('del的时候运行我啊')
    
        AAA = property(get_AAA,set_AAA,del_AAA)
    f1 = Foo()
    f1.AAA
    f1.AAA = 'jinling'
    del f1.AAA
    

      

     

     

    一个奋斗中的产品小白
  • 相关阅读:
    leetcode680
    leetcode558
    leetcode840
    leetcode703
    leetcode836
    leetcode704
    leetcode849
    leetcode707
    2019-10-26-Inno-Setup-安装包脚本-Run-的-Flags-标记
    2019-8-30-C#-从零开始写-SharpDx-应用-笔刷
  • 原文地址:https://www.cnblogs.com/dabai123/p/11668896.html
Copyright © 2020-2023  润新知